├── .bumpversion.cfg
├── .github
└── workflows
│ └── release.yml
├── .gitignore
├── .readthedocs.yml
├── .travis.yml
├── LICENSE
├── MANIFEST.in
├── README.rst
├── allinpay
├── __init__.py
├── client
│ ├── __init__.py
│ ├── api
│ │ ├── __init__.py
│ │ ├── base.py
│ │ ├── gateway.py
│ │ ├── posol.py
│ │ ├── prescanpay.py
│ │ ├── qpay.py
│ │ ├── tranx.py
│ │ ├── trxfile.py
│ │ ├── unitorder.py
│ │ └── verify.py
│ └── base.py
└── core
│ ├── __init__.py
│ ├── exceptions.py
│ └── utils.py
├── dev-requirements.txt
├── docs
├── Makefile
├── changelog.rst
├── client
│ ├── api
│ │ ├── gateway.rst
│ │ ├── posol.rst
│ │ ├── prescanpay.rst
│ │ ├── qpay.rst
│ │ ├── tranx.rst
│ │ ├── trxfile.rst
│ │ ├── unitorder.rst
│ │ └── verify.rst
│ └── index.rst
├── conf.py
├── index.rst
└── install.rst
├── requirements.txt
├── setup.cfg
├── setup.py
├── tests
└── test_utils.py
└── tox.ini
/.bumpversion.cfg:
--------------------------------------------------------------------------------
1 | [bumpversion]
2 | files = setup.py allinpay/__init__.py
3 | commit = True
4 | tag = True
5 | current_version = 1.1.10
6 |
--------------------------------------------------------------------------------
/.github/workflows/release.yml:
--------------------------------------------------------------------------------
1 | # This workflows will upload a Python Package using Twine when a release is created
2 | # For more information see: https://help.github.com/en/actions/language-and-framework-guides/using-python-with-github-actions#publishing-to-package-registries
3 |
4 | name: release
5 |
6 | on:
7 | push:
8 | tags:
9 | - v*
10 |
11 | jobs:
12 | deploy:
13 |
14 | runs-on: ubuntu-latest
15 |
16 | steps:
17 | - uses: actions/checkout@v2
18 | - name: Set up Python
19 | uses: actions/setup-python@v1
20 | with:
21 | python-version: '3.x'
22 | - name: Install dependencies
23 | run: |
24 | python -m pip install --upgrade pip
25 | pip install setuptools wheel twine django
26 | - name: Build and publish
27 | env:
28 | TWINE_USERNAME: ${{ secrets.PYPI_USERNAME }}
29 | TWINE_PASSWORD: ${{ secrets.PYPI_PASSWORD }}
30 | run: |
31 | python setup.py sdist bdist_wheel
32 | twine upload --skip-existing dist/*
33 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # Byte-compiled / optimized / DLL files
2 | __pycache__/
3 | *.py[cod]
4 | *$py.class
5 |
6 | # C extensions
7 | *.so
8 |
9 | # Distribution / packaging
10 | .Python
11 | env/
12 | build/
13 | develop-eggs/
14 | dist/
15 | downloads/
16 | eggs/
17 | .eggs/
18 | lib/
19 | lib64/
20 | parts/
21 | sdist/
22 | var/
23 | *.egg-info/
24 | .installed.cfg
25 | *.egg
26 |
27 | # PyInstaller
28 | # Usually these files are written by a python script from a template
29 | # before PyInstaller builds the exe, so as to inject date/other infos into it.
30 | *.manifest
31 | *.spec
32 |
33 | # Installer logs
34 | pip-log.txt
35 | pip-delete-this-directory.txt
36 |
37 | # Unit test / coverage reports
38 | htmlcov/
39 | .tox/
40 | .coverage
41 | .coverage.*
42 | .cache
43 | nosetests.xml
44 | coverage.xml
45 | *,cover
46 | .hypothesis/
47 |
48 | # Translations
49 | *.mo
50 | *.pot
51 |
52 | # Django stuff:
53 | *.log
54 | local_settings.py
55 |
56 | # Flask stuff:
57 | instance/
58 | .webassets-cache
59 |
60 | # Scrapy stuff:
61 | .scrapy
62 |
63 | # Sphinx documentation
64 | docs/_build/
65 |
66 | # PyBuilder
67 | target/
68 |
69 | # IPython Notebook
70 | .ipynb_checkpoints
71 |
72 | # pyenv
73 | .python-version
74 |
75 | # celery beat schedule file
76 | celerybeat-schedule
77 |
78 | # dotenv
79 | .env
80 |
81 | # virtualenv
82 | venv/
83 | ENV/
84 |
85 | # Spyder project settings
86 | .spyderproject
87 |
88 | # Rope project settings
89 | .ropeproject
90 | .pytest_cache
91 |
92 | .idea/
93 |
94 | .DS_Store
95 |
96 |
--------------------------------------------------------------------------------
/.readthedocs.yml:
--------------------------------------------------------------------------------
1 | formats:
2 | - none
3 | python:
4 | version: 3
5 | pip_install: true
6 |
--------------------------------------------------------------------------------
/.travis.yml:
--------------------------------------------------------------------------------
1 | language: python
2 |
3 | # Use container-based infrastructure
4 | sudo: false
5 |
6 | matrix:
7 | include:
8 | - env: TOX_ENV=py27
9 | python: 2.7
10 | - env: TOX_ENV=py34
11 | python: 3.4
12 | - env: TOX_ENV=py35
13 | python: 3.5
14 | - env: TOX_ENV=py36
15 | python: 3.6
16 | - env: TOX_ENV=py37
17 | python: 3.7
18 | - env: TOX_ENV=pypy
19 | python: "pypy"
20 | - env: TOX_ENV=pypy3
21 | python: "pypy3"
22 |
23 | cache:
24 | directories:
25 | - $HOME/.cache/pip
26 |
27 | install:
28 | - pip install tox
29 | - pip install "flake8>=3.7"
30 |
31 | before_script:
32 | - "flake8 ."
33 |
34 | script:
35 | tox -e $TOX_ENV
36 |
37 | after_success:
38 | - |
39 | if [[ "${TRAVIS_TAG:-}" != "" && "$TOX_ENV" == "py36" ]]; then
40 | python3.6 setup.py sdist bdist_wheel;
41 | python3.6 -m pip install twine;
42 | python3.6 -m twine upload --skip-existing dist/*;
43 | fi
44 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include README.rst
2 | include requirements.txt
--------------------------------------------------------------------------------
/README.rst:
--------------------------------------------------------------------------------
1 | #######################
2 | AllInPay Sdk for Python
3 | #######################
4 | .. image:: https://travis-ci.org/007gzs/pyallinpay.svg?branch=master
5 | :target: https://travis-ci.org/007gzs/pyallinpay
6 | .. image:: https://img.shields.io/pypi/v/pyallinpay.svg
7 | :target: https://pypi.org/project/pyallinpay
8 |
9 | 通联支付 Python SDK。
10 | `【阅读文档】 `_。
11 |
12 | ********
13 | 安装
14 | ********
15 |
16 | 目前 PyAllInPay 支持的 Python 环境有 2.7, 3.4, 3.5, 3.6, 3.7 和 pypy。
17 |
18 | 为了简化安装过程,推荐使用 pip 进行安装
19 |
20 | .. code-block:: bash
21 |
22 | pip install pyallinpay
23 |
24 | 升级 pyallinpay 到新版本::
25 |
26 | pip install -U pyallinpay
27 |
28 | 如果需要安装 GitHub 上的最新代码::
29 |
30 | pip install https://github.com/007gzs/pyallinpay/archive/master.zip
31 |
32 |
--------------------------------------------------------------------------------
/allinpay/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | from .client import AllInPayClient, AllInPayTestClient # NOQA
5 |
6 |
7 | __version__ = '1.1.10'
8 |
--------------------------------------------------------------------------------
/allinpay/client/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | import logging
5 |
6 | from allinpay.core.exceptions import AllInPayClientException
7 | from . import api
8 | from .base import BaseClient
9 | from ..core.utils import AllInPayMd5Signer, AllInPayRsaSigner, AllInPaySm2Signer, random_string, to_text
10 |
11 | logger = logging.getLogger(__name__)
12 |
13 | SIGNER_CONFIG = {
14 | "md5": (AllInPayMd5Signer, "signer_key", "signer_key"),
15 | "rsa": (AllInPayRsaSigner, "signer_key", "PUBLIC_RSA_KEY"),
16 | "sm2": (AllInPaySm2Signer, "signer_key", "PUBLIC_SM2_KEY"),
17 | }
18 |
19 |
20 | class AllInPayClient(BaseClient):
21 | """
22 | 通联支付生产环境
23 | """
24 | gateway = api.Gateway()
25 | posol = api.Posol()
26 | prescanpay = api.PreScanPay()
27 | qpay = api.QPay()
28 | tranx = api.Tranx()
29 | trxfile = api.Trxfile()
30 | unitorder = api.UnitOrder()
31 | verify = api.Verify()
32 | PUBLIC_RSA_KEY = AllInPayRsaSigner.get_public_key(
33 | "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCm9OV6zH5DYH/ZnAVYHscEELdCNfNTHGuBv1nYYEY9FrOzE0/4kLl9f7Y9dkWHlc2ocDwb"
34 | "rFSm0Vqz0q2rJPxXUYBCQl5yW3jzuKSXif7q1yOwkFVtJXvuhf5WRy+1X5FOFoMvS7538No0RpnLzmNi3ktmiqmhpcY/1pmt20FHQQIDAQAB"
35 | )
36 | PUBLIC_SM2_KEY = AllInPaySm2Signer.get_public_key(
37 | "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEBQicgWm0KAMqhO3bdqMUEDrKQv"
38 | "Yg8cCXHhdGwq7CGE6oJDzJ1P/94HpuVdBf1KidmPxr7HOH+0DAnpeCcx9TcQ=="
39 | )
40 |
41 | def __init__(self, app_id, cus_id, signer_key, timeout=None, sign_type="md5", public_key=None):
42 | sign_type = sign_type.lower()
43 | assert sign_type in SIGNER_CONFIG
44 | super(AllInPayClient, self).__init__(timeout)
45 | self.app_id = app_id
46 | self.cus_id = cus_id
47 | self.sign_type = sign_type
48 | signer_cls = SIGNER_CONFIG[sign_type][0]
49 | self.signer_key = signer_cls.get_private_key(signer_key)
50 | if public_key is not None:
51 | setattr(self, SIGNER_CONFIG[sign_type][2], signer_cls.get_public_key(public_key))
52 |
53 | def get_signer_cls(self, sign_type):
54 | if sign_type is None:
55 | sign_type = self.sign_type
56 | sign_type = sign_type.lower()
57 | assert sign_type in SIGNER_CONFIG
58 | signer_cls, private_key, public_key = SIGNER_CONFIG[sign_type]
59 | private_key = getattr(self, private_key)
60 | public_key = getattr(self, public_key)
61 | return signer_cls, private_key, public_key
62 |
63 | def add_sign(self, data, random_str_key="randomstr", sign_key="sign", sign_type=None):
64 | signer_cls, private_key, public_key = self.get_signer_cls(sign_type)
65 | if random_str_key and random_str_key not in data:
66 | data[random_str_key] = random_string()
67 | signer = signer_cls(delimiter=b'&', key=private_key)
68 | for k, v in data.items():
69 | v = to_text(v)
70 | if v:
71 | signer.add_data("%s=%s" % (k, v))
72 | data[sign_key] = signer.signature
73 | return data
74 |
75 | def check_sign(self, data, sign_key="sign", sign_type=None):
76 | signer_cls, private_key, public_key = self.get_signer_cls(sign_type)
77 | sign = ''
78 | signer = signer_cls(delimiter=b'&', key=public_key)
79 | for k, v in data.items():
80 | v = to_text(v)
81 | if k == sign_key:
82 | sign = v
83 | elif v:
84 | signer.add_data("%s=%s" % (k, v))
85 | if sign.lower() != signer.signature:
86 | raise AllInPayClientException("SIGNAUTHERR", "签名错误")
87 |
88 | def _handle_pre_request(self, method, uri, kwargs):
89 | # if 'access_token=' in uri or 'access_token' in kwargs.get('params', {}):
90 | # raise ValueError("uri参数中不允许有access_token: " + uri)
91 | # uri = '%s%saccess_token=%s' % (uri, '&' if '?' in uri else '?', self.access_token)
92 | return method, uri, kwargs
93 |
94 | def _handle_request_except(self, e, func, *args, **kwargs):
95 | # if e.errcode in (33001, 40001, 42001, 40014):
96 | # self.cache.access_token.delete()
97 | # if self.auto_retry:
98 | # return func(*args, **kwargs)
99 | raise e
100 |
101 |
102 | class AllInPayTestClient(AllInPayClient):
103 | """
104 | 通联支付测试环境
105 | """
106 | API_BASE_URL = 'https://test.allinpaygd.com/'
107 | SYB_API_BASE_URL = 'https://test.allinpaygd.com/'
108 | PUBLIC_RSA_KEY = AllInPayRsaSigner.get_public_key(
109 | "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDYXfu4b7xgDSmEGQpQ8Sn3RzFgl5CE4gL4TbYrND4FtCYOrvbgLijkdFgIrVVWi2hUW4K0"
110 | "PwBsmlYhXcbR+JSmqv9zviVXZiym0lK3glJGVCN86r9EPvNTusZZPm40TOEKMVENSYaUjCxZ7JzeZDfQ4WCeQQr2xirqn6LdJjpZ5wIDAQAB"
111 | )
112 | PUBLIC_SM2_KEY = AllInPaySm2Signer.get_public_key(
113 | "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAE/BnA8BawehBtH0ksPyayo4pmzL"
114 | "/u1FQ2sZcqwOp6bjVqQX4tjo930QAvHZPJ2eez8sCz/RYghcqv4LvMq+kloQ=="
115 | )
116 |
--------------------------------------------------------------------------------
/allinpay/client/api/__init__.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | from .unitorder import UnitOrder # NOQA
5 | from .tranx import Tranx # NOQA
6 | from .gateway import Gateway # NOQA
7 | from .prescanpay import PreScanPay # NOQA
8 | from .qpay import QPay # NOQA
9 | from .posol import Posol # NOQA
10 | from .trxfile import Trxfile # NOQA
11 | from .verify import Verify # NOQA
12 |
--------------------------------------------------------------------------------
/allinpay/client/api/base.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import absolute_import, unicode_literals
3 |
4 |
5 | class AllInPayBaseAPI(object):
6 |
7 | API_BASE_URL = None
8 | SYB_API_BASE_URL = None
9 |
10 | def __init__(self, client=None):
11 | self._client = client
12 | if self.SYB_API_BASE_URL is None and self._client is not None:
13 | self.SYB_API_BASE_URL = self._client.SYB_API_BASE_URL
14 |
15 | def _get(self, url, params=None, **kwargs):
16 | if self.API_BASE_URL and 'api_base_url' not in kwargs:
17 | kwargs['api_base_url'] = self.API_BASE_URL
18 | return self._client.get(url, params, **kwargs)
19 |
20 | def _post(self, url, data=None, params=None, **kwargs):
21 | if self.API_BASE_URL and 'api_base_url' not in kwargs:
22 | kwargs['api_base_url'] = self.API_BASE_URL
23 | return self._client.post(url, data, params, **kwargs)
24 |
25 | def add_sign(self, data, random_str_key="randomstr", sign_key="sign"):
26 | return self._client.add_sign(data, random_str_key, sign_key)
27 |
28 | @property
29 | def cus_id(self):
30 | return self._client.cus_id
31 |
32 | @property
33 | def app_id(self):
34 | return self._client.app_id
35 |
--------------------------------------------------------------------------------
/allinpay/client/api/gateway.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | from optionaldict import optionaldict
5 |
6 | from .base import AllInPayBaseAPI
7 |
8 |
9 | class Gateway(AllInPayBaseAPI):
10 | """
11 | 网关支付
12 | """
13 | def pay(self, orderid, trxamt, paytype, returl=None, notifyurl=None,
14 | validtime=720, goodsid=None, goodsinf=None, gateid=None, limitpay=None, charset='UTF-8'):
15 | """
16 | 网关支付 - 订单提交接口(商户网站->支付网关)
17 | https://aipboss.allinpay.com/know/devhelp/home.php?id=73
18 |
19 | :param orderid: 商户唯一订单号
20 | :param trxamt: 付款金额
21 | :param paytype: 交易类型
22 | :param returl: 页面跳转同步通知页面路径
23 | :param notifyurl: 服务器异步通知页面路径
24 | :param validtime: 有效时间
25 | :param goodsid: 商品号
26 | :param goodsinf: 商品描述信息
27 | :param gateid: 支付银行
28 | :param limitpay: 支付限制
29 | :param charset: 参数字符编码集
30 | """
31 | if not returl and not notifyurl:
32 | raise ValueError("returl和notifyurl不能同时为空")
33 | data = optionaldict({
34 | "cusid": self.cus_id,
35 | "appid": self.app_id,
36 | "orderid": orderid,
37 | "trxamt": trxamt,
38 | "paytype": paytype,
39 | "returl": returl,
40 | "notifyurl": notifyurl,
41 | "validtime": validtime,
42 | "goodsid": goodsid,
43 | "goodsinf": goodsinf,
44 | "gateid": gateid,
45 | "limitpay": limitpay,
46 | "charset": charset
47 | })
48 | self.add_sign(data)
49 | return self._post('/apiweb/gateway/pay', data)
50 |
51 | def query(self, orderid=None, trxid=None):
52 | """
53 | 网关支付 - 交易查询接口
54 | https://aipboss.allinpay.com/know/devhelp/home.php?id=73
55 |
56 | :param orderid: 商户订单号
57 | :param trxid: 平台交易流水
58 | """
59 | if not orderid and not trxid:
60 | raise ValueError("orderid和trxid必填其一")
61 | data = optionaldict({
62 | "cusid": self.cus_id,
63 | "appid": self.app_id,
64 | "orderid": orderid,
65 | "trxid": trxid
66 | })
67 | self.add_sign(data)
68 | return self._post('/apiweb/gateway/query', data)
69 |
70 | def refund(self, reqsn, trxamt, orderid=None, trxid=None, notifyurl=None):
71 | """
72 | 网关支付 - 订单退款接口
73 | https://aipboss.allinpay.com/know/devhelp/home.php?id=73
74 |
75 | :param reqsn: 商户退款流水
76 | :param trxamt: 退款金额
77 | :param orderid: 商户订单号
78 | :param trxid: 平台交易流水
79 | :param notifyurl: 服务器异步通知页面路径
80 | """
81 | if not orderid and not trxid:
82 | raise ValueError("orderid和trxid必填其一")
83 | data = optionaldict({
84 | "cusid": self.cus_id,
85 | "appid": self.app_id,
86 | "reqsn": reqsn,
87 | "trxamt": trxamt,
88 | "orderid": orderid,
89 | "trxid": trxid,
90 | "notifyurl": notifyurl
91 | })
92 | self.add_sign(data)
93 | return self._post('/apiweb/gateway/refund', data)
94 |
--------------------------------------------------------------------------------
/allinpay/client/api/posol.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | from optionaldict import optionaldict
5 |
6 | from .base import AllInPayBaseAPI
7 |
8 |
9 | class Posol(AllInPayBaseAPI):
10 | """
11 | 协同收银
12 | """
13 |
14 | def authfin(self, reqsn, trxid, trxamt, orgid=None, version='11'):
15 | """
16 | 预授权完成
17 | https://aipboss.allinpay.com/know/devhelp/home.php?id=261
18 |
19 | :param reqsn: 商户预授权完成交易流水号
20 | :param trxid: 交易单号
21 | :param trxamt: 交易金额
22 | :param orgid: 集团商户号
23 | :param version: 版本号
24 | """
25 | data = optionaldict({
26 | "cusid": self.cus_id,
27 | "appid": self.app_id,
28 | "orgid": orgid,
29 | "reqsn": reqsn,
30 | "trxid": trxid,
31 | "trxamt": trxamt,
32 | "version": version
33 | })
34 | self.add_sign(data)
35 | return self._post("/apiweb/posol/authfin", data)
36 |
37 | def refund(self, reqsn, trxid, trxamt, orgid=None, version='11', remark=None):
38 | """
39 | 交易退货
40 | https://aipboss.allinpay.com/know/devhelp/home.php?id=262
41 |
42 | :param reqsn: 商户退货交易流水号
43 | :param trxid: 交易单号
44 | :param trxamt: 退款金额
45 | :param orgid: 集团商户号
46 | :param version: 版本号
47 | :param remark: 交易备注
48 | """
49 | data = optionaldict({
50 | "cusid": self.cus_id,
51 | "appid": self.app_id,
52 | "orgid": orgid,
53 | "reqsn": reqsn,
54 | "trxid": trxid,
55 | "trxamt": trxamt,
56 | "version": version,
57 | "remark": remark
58 | })
59 | self.add_sign(data)
60 | return self._post("/apiweb/posol/refund", data)
61 |
62 | def cancel(self, reqsn, trxid, trxamt, orgid=None, version='11'):
63 | """
64 | 交易撤销
65 | https://aipboss.allinpay.com/know/devhelp/home.php?id=263
66 |
67 | :param reqsn: 商户撤销交易流水号
68 | :param trxid: 交易单号
69 | :param trxamt: 撤销金额
70 | :param orgid: 集团商户号
71 | :param version: 版本号
72 | """
73 | data = optionaldict({
74 | "cusid": self.cus_id,
75 | "appid": self.app_id,
76 | "orgid": orgid,
77 | "reqsn": reqsn,
78 | "trxid": trxid,
79 | "trxamt": trxamt,
80 | "version": version
81 | })
82 | self.add_sign(data)
83 | return self._post("/apiweb/posol/cancel", data)
84 |
85 | def query(self, reqsn=None, trxid=None, orgid=None, version='11', remark=None):
86 | """
87 | 交易查询
88 | https://aipboss.allinpay.com/know/devhelp/home.php?id=264
89 |
90 | :param orgid: 集团商户号
91 | :param reqsn: 订单号
92 | :param trxid: 收银宝交易流水
93 | :param version: 版本号
94 | :param remark: 交易备注
95 | """
96 | if not reqsn and not trxid:
97 | raise ValueError("reqsn和trxid不能同时为空")
98 | data = optionaldict({
99 | "cusid": self.cus_id,
100 | "appid": self.app_id,
101 | "orgid": orgid,
102 | "reqsn": reqsn,
103 | "trxid": trxid,
104 | "version": version,
105 | "remark": remark
106 | })
107 | self.add_sign(data)
108 | return self._post("/apiweb/posol/query", data)
109 |
--------------------------------------------------------------------------------
/allinpay/client/api/prescanpay.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | from optionaldict import optionaldict
5 |
6 | from .base import AllInPayBaseAPI
7 |
8 |
9 | class PreScanPay(AllInPayBaseAPI):
10 | """
11 | 网上收银预消费
12 | """
13 | def pay(self, reqsn, trxamt, paytype, body=None, validtime=5,
14 | authcode=None, acct=None, notify_url=None, limit_pay=None,
15 | sub_appid=None, subbranch=None, cusip=None, version='12', remark=None):
16 | """
17 | 网上收银预消费 - 扫码预消费
18 | https://aipboss.allinpay.com/know/devhelp/home.php?id=362
19 |
20 | :param reqsn: 商户交易单号
21 | :param trxamt: 交易金额
22 | :param paytype: 交易方式
23 | :param body: 订单标题
24 | :param validtime: 有效时间
25 | :param authcode: 支付授权码
26 | :param acct: 支付平台用户标识
27 | :param notify_url: 交易结果通知地址
28 | :param limit_pay: 支付限制
29 | :param sub_appid: 微信子appid
30 | :param subbranch: 门店号
31 | :param cusip: 终端ip
32 | :param version: 版本号
33 | :param remark: 备注
34 | """
35 | data = optionaldict({
36 | "cusid": self.cus_id,
37 | "appid": self.app_id,
38 | "reqsn": reqsn,
39 | "trxamt": trxamt,
40 | "paytype": paytype,
41 | "body": body,
42 | "validtime": validtime,
43 | "authcode": authcode,
44 | "acct": acct,
45 | "notify_url": notify_url,
46 | "limit_pay": limit_pay,
47 | "sub_appid": sub_appid,
48 | "subbranch": subbranch,
49 | "cusip": cusip,
50 | "version": version,
51 | "remark": remark
52 | })
53 | self.add_sign(data)
54 | return self._post('/apiweb/prescanpay/pay', data)
55 |
56 | def finish(self, reqsn, trxamt, oldtrxid, asinfo=None, version='12'):
57 | """
58 | 网上收银预消费 - 扫码预消费完成
59 | https://aipboss.allinpay.com/know/devhelp/home.php?id=363
60 |
61 | :param reqsn: 商户完成交易单号
62 | :param trxamt: 交易金额
63 | :param oldtrxid: 预消费交易流水
64 | :param asinfo: 分账信息
65 | :param version: 版本号
66 | """
67 | data = optionaldict({
68 | "cusid": self.cus_id,
69 | "appid": self.app_id,
70 | "reqsn": reqsn,
71 | "trxamt": trxamt,
72 | "oldtrxid": oldtrxid,
73 | "asinfo": asinfo,
74 | "version": version
75 | })
76 | self.add_sign(data)
77 | return self._post('/apiweb/prescanpay/finish', data)
78 |
79 | def cancel(self, reqsn, trxamt, oldtrxid, version='12'):
80 | """
81 | 网上收银预消费 - 扫码预消费交易回退
82 | https://aipboss.allinpay.com/know/devhelp/home.php?id=364
83 |
84 | :param reqsn: 商户撤销交易单号
85 | :param trxamt: 交易金额
86 | :param oldtrxid: 预消费交易流水
87 | :param version: 版本号
88 | """
89 | data = optionaldict({
90 | "cusid": self.cus_id,
91 | "appid": self.app_id,
92 | "reqsn": reqsn,
93 | "trxamt": trxamt,
94 | "oldtrxid": oldtrxid,
95 | "version": version
96 | })
97 | self.add_sign(data)
98 | return self._post('/apiweb/prescanpay/cancel', data)
99 |
100 | def refund(self, reqsn, trxamt, oldtrxid, version='12', remark=None):
101 | """
102 | 网上收银预消费 - 扫码预消费完成交易退款
103 | https://aipboss.allinpay.com/know/devhelp/home.php?id=365
104 | """
105 | data = optionaldict({
106 | "cusid": self.cus_id,
107 | "appid": self.app_id,
108 | "reqsn": reqsn,
109 | "trxamt": trxamt,
110 | "oldtrxid": oldtrxid,
111 | "version": version,
112 | "remark": remark
113 | })
114 | self.add_sign(data)
115 | return self._post('/apiweb/prescanpay/refund', data)
116 |
117 | def query(self, reqsn=None, trxid=None, version="12"):
118 | """
119 | 网上收银预消费 - 扫码预消费查询
120 | https://aipboss.allinpay.com/know/devhelp/home.php?id=366
121 |
122 | :param reqsn: 商户预消费订单号
123 | :param trxid: 平台预消费交易流水
124 | :param version: 版本号
125 | """
126 | if not reqsn and not trxid:
127 | raise ValueError("reqsn和trxid必填其一")
128 | data = optionaldict({
129 | "cusid": self.cus_id,
130 | "appid": self.app_id,
131 | "reqsn": reqsn,
132 | "trxid": trxid,
133 | "version": version
134 | })
135 | self.add_sign(data)
136 | return self._post('/apiweb/prescanpay/query', data)
137 |
--------------------------------------------------------------------------------
/allinpay/client/api/qpay.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | import datetime
5 |
6 | from optionaldict import optionaldict
7 |
8 | from .base import AllInPayBaseAPI
9 |
10 |
11 | class QPay(AllInPayBaseAPI):
12 | """
13 | 快捷支付
14 | """
15 | def agreeapply(self, meruserid, accttype, acctno, idno, acctname, mobile,
16 | validdate=None, cvv2=None, reqip=None, version='11'):
17 | """
18 | 快捷支付 - 签约申请
19 | https://aipboss.allinpay.com/know/devhelp/home.php?id=136
20 |
21 | :param meruserid: 商户用户号
22 | :param accttype: 卡类型
23 | :param acctno: 银行卡号
24 | :param idno: 证件号
25 | :param acctname: 户名
26 | :param mobile: 手机号码
27 | :param validdate: 有效期
28 | :param cvv2: Cvv2
29 | :param reqip: 请求ip
30 | :param version: 版本号
31 | """
32 | data = optionaldict({
33 | "cusid": self.cus_id,
34 | "appid": self.app_id,
35 | "reqip": reqip,
36 | "version": version,
37 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
38 | "meruserid": meruserid,
39 | "accttype": accttype,
40 | "acctno": acctno,
41 | "idno": idno,
42 | "acctname": acctname,
43 | "mobile": mobile,
44 | "validdate": validdate,
45 | "cvv2": cvv2
46 | })
47 | self.add_sign(data)
48 | return self._post('/apiweb/qpay/agreeapply', data)
49 |
50 | def agreeconfirm(self, meruserid, accttype, acctno, idno, acctname, mobile, smscode, thpinfo,
51 | validdate=None, cvv2=None, reqip=None, version='11'):
52 | """
53 | 快捷支付 - 签约申请确认
54 | https://aipboss.allinpay.com/know/devhelp/home.php?id=137
55 |
56 | :param meruserid: 商户用户号
57 | :param accttype: 卡类型
58 | :param acctno: 银行卡号
59 | :param idno: 证件号
60 | :param acctname: 户名
61 | :param mobile: 手机号码
62 | :param smscode: 短信验证码
63 | :param thpinfo: 交易透传信息
64 | :param validdate: 有效期
65 | :param cvv2: Cvv2
66 | :param reqip: 请求ip
67 | :param version: 版本号
68 | """
69 | data = optionaldict({
70 | "cusid": self.cus_id,
71 | "appid": self.app_id,
72 | "reqip": reqip,
73 | "version": version,
74 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
75 | "meruserid": meruserid,
76 | "accttype": accttype,
77 | "acctno": acctno,
78 | "idno": idno,
79 | "acctname": acctname,
80 | "mobile": mobile,
81 | "smscode": smscode,
82 | "thpinfo": thpinfo,
83 | "validdate": validdate,
84 | "cvv2": cvv2
85 | })
86 | self.add_sign(data)
87 | return self._post('/apiweb/qpay/agreeconfirm', data)
88 |
89 | def payapplyagree(self, orderid, agreeid, amount, subject, notifyurl, validtime=None, trxreserve=None, asinfo=None,
90 | currency="CNY", reqip=None, version='11'):
91 | """
92 | 快捷支付 - 商户支付申请
93 | https://aipboss.allinpay.com/know/devhelp/home.php?id=139
94 |
95 | :param orderid: 商户订单号
96 | :param agreeid: 协议编号
97 | :param amount: 订单金额
98 | :param subject: 订单内容
99 | :param notifyurl: 交易结果通知地址
100 | :param validtime: 有效时间
101 | :param trxreserve: 交易备注
102 | :param asinfo: 分账信息
103 | :param currency: 币种
104 | :param reqip: 请求ip
105 | :param version: 版本号
106 | """
107 | data = optionaldict({
108 | "cusid": self.cus_id,
109 | "appid": self.app_id,
110 | "reqip": reqip,
111 | "version": version,
112 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
113 | "orderid": orderid,
114 | "agreeid": agreeid,
115 | "amount": amount,
116 | "subject": subject,
117 | "notifyurl": notifyurl,
118 | "validtime": validtime,
119 | "trxreserve": trxreserve,
120 | "asinfo": asinfo,
121 | "currency": currency
122 | })
123 | self.add_sign(data)
124 | return self._post('/apiweb/qpay/payapplyagree', data)
125 |
126 | def payagreeconfirm(self, orderid, agreeid, thpinfo, smscode=None, reqip=None, version='11'):
127 | """
128 | 快捷支付 - 支付确认
129 | https://aipboss.allinpay.com/know/devhelp/home.php?id=140
130 |
131 | :param orderid: 订单号
132 | :param agreeid: 协议编号
133 | :param thpinfo: 交易透传信息
134 | :param smscode: 短信验证码
135 | :param reqip: 请求ip
136 | :param version: 版本号
137 | """
138 | data = optionaldict({
139 | "cusid": self.cus_id,
140 | "appid": self.app_id,
141 | "reqip": reqip,
142 | "version": version,
143 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
144 | "orderid": orderid,
145 | "agreeid": agreeid,
146 | "thpinfo": thpinfo,
147 | "smscode": smscode
148 | })
149 | self.add_sign(data)
150 | return self._post('/apiweb/qpay/payagreeconfirm', data)
151 |
152 | def paysmsagree(self, orderid, agreeid=None, thpinfo=None, reqip=None, version='11'):
153 | """
154 | 快捷支付 - 重新获取支付短信
155 | https://aipboss.allinpay.com/know/devhelp/home.php?id=141
156 |
157 | :param orderid: 商户订单号
158 | :param agreeid: 协议编号
159 | :param thpinfo: 交易透传信息
160 | :param reqip: 请求ip
161 | :param version: 版本号
162 | """
163 | data = optionaldict({
164 | "cusid": self.cus_id,
165 | "appid": self.app_id,
166 | "reqip": reqip,
167 | "version": version,
168 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
169 | "orderid": orderid,
170 | "agreeid": agreeid,
171 | "thpinfo": thpinfo
172 | })
173 | self.add_sign(data)
174 | return self._post('/apiweb/qpay/paysmsagree', data)
175 |
176 | def agreequery(self, meruserid, reqip=None, version='11'):
177 | """
178 | 快捷支付 - 协议查询接口
179 | https://aipboss.allinpay.com/know/devhelp/home.php?id=213
180 |
181 | :param meruserid: 商户用户号
182 | :param reqip: 请求ip
183 | :param version: 版本号
184 | """
185 | data = optionaldict({
186 | "cusid": self.cus_id,
187 | "appid": self.app_id,
188 | "reqip": reqip,
189 | "version": version,
190 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
191 | "meruserid": meruserid
192 | })
193 | self.add_sign(data)
194 | return self._post('/apiweb/qpay/agreequery', data, result_processor=lambda x: x['agreelist'])
195 |
196 | def unbind(self, agreeid, reqip=None, version='11'):
197 | """
198 | 快捷支付 - 银行卡解绑
199 | https://aipboss.allinpay.com/know/devhelp/home.php?id=142
200 |
201 | :param agreeid: 协议编号
202 | :param reqip: 请求ip
203 | :param version: 版本号
204 | """
205 | data = optionaldict({
206 | "cusid": self.cus_id,
207 | "appid": self.app_id,
208 | "reqip": reqip,
209 | "version": version,
210 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
211 | "agreeid": agreeid
212 | })
213 | self.add_sign(data)
214 | return self._post('/apiweb/qpay/unbind', data)
215 |
216 | def cancel(self, orderid, trxamt, oldorderid=None, oldtrxid=None, reqip=None, version='11'):
217 | """
218 | 快捷支付 - 交易撤销
219 | https://aipboss.allinpay.com/know/devhelp/home.php?id=143
220 |
221 | :param orderid: 商户退款交易单号
222 | :param trxamt: 交易金额
223 | :param oldorderid: 原交易单号
224 | :param oldtrxid: 原交易流水
225 | :param reqip: 请求ip
226 | :param version: 版本号
227 | """
228 | if not oldorderid and not oldtrxid:
229 | raise ValueError("oldorderid和oldtrxid必填其一")
230 | data = optionaldict({
231 | "cusid": self.cus_id,
232 | "appid": self.app_id,
233 | "reqip": reqip,
234 | "version": version,
235 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
236 | "orderid": orderid,
237 | "trxamt": trxamt,
238 | "oldorderid": oldorderid,
239 | "oldtrxid": oldtrxid
240 | })
241 | self.add_sign(data)
242 | return self._post('/apiweb/qpay/cancel', data)
243 |
244 | def refund(self, orderid, trxamt, oldorderid=None, oldtrxid=None, reqip=None, version='11'):
245 | """
246 | 快捷支付 - 交易退款
247 | https://aipboss.allinpay.com/know/devhelp/home.php?id=144
248 |
249 | :param orderid: 商户退款交易单号
250 | :param trxamt: 交易金额
251 | :param oldorderid: 原交易单号
252 | :param oldtrxid: 原交易流水
253 | :param reqip: 请求ip
254 | :param version: 版本号
255 | """
256 | if not oldorderid and not oldtrxid:
257 | raise ValueError("oldorderid和oldtrxid必填其一")
258 | data = optionaldict({
259 | "cusid": self.cus_id,
260 | "appid": self.app_id,
261 | "reqip": reqip,
262 | "version": version,
263 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
264 | "orderid": orderid,
265 | "trxamt": trxamt,
266 | "oldorderid": oldorderid,
267 | "oldtrxid": oldtrxid
268 | })
269 | self.add_sign(data)
270 | return self._post('/apiweb/qpay/refund', data)
271 |
272 | def query(self, orderid=None, trxid=None, reqip=None, version='11'):
273 | """
274 | 快捷支付 - 交易查询
275 | https://aipboss.allinpay.com/know/devhelp/home.php?id=145
276 |
277 | :param orderid: 商户的交易订单号
278 | :param trxid: 平台交易流水
279 | :param reqip: 请求ip
280 | :param version: 版本号
281 | """
282 | if not orderid and not trxid:
283 | raise ValueError("orderid和trxid必填其一")
284 | data = optionaldict({
285 | "cusid": self.cus_id,
286 | "appid": self.app_id,
287 | "reqip": reqip,
288 | "version": version,
289 | "reqtime": datetime.datetime.now().strftime("%Y%m%d%H%M%S"),
290 | "orderid": orderid,
291 | "trxid": trxid
292 | })
293 | self.add_sign(data)
294 | return self._post('/apiweb/qpay/query', data)
295 |
--------------------------------------------------------------------------------
/allinpay/client/api/tranx.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | from six.moves.urllib import parse
5 | from optionaldict import optionaldict
6 |
7 | from .base import AllInPayBaseAPI
8 |
9 |
10 | class Tranx(AllInPayBaseAPI):
11 | """
12 | 终端订单支付, 当面付订单支付
13 | """
14 |
15 | def queryorder(self, trxdate=None, orderid=None, trxid=None, termno=None, resendnotify=False):
16 | """
17 | 终端订单支付-订单交易结果查询
18 | https://aipboss.allinpay.com/know/devhelp/home.php?id=100
19 | 当面付订单支付-交易查询
20 | https://aipboss.allinpay.com/know/devhelp/home.php?id=207
21 |
22 | :param trxdate: 交易日期
23 | :param orderid: 订单号
24 | :param trxid: 收银宝交易流水
25 | :param termno: 终端号
26 | :param resendnotify: 是否重发交易结果通知
27 | """
28 | if not orderid and not trxid:
29 | raise ValueError("orderid和trxid不能同时为空")
30 | data = optionaldict({
31 | "cusid": self.cus_id,
32 | "appid": self.app_id,
33 | "trxdate": trxdate,
34 | "orderid": orderid,
35 | "trxid": trxid,
36 | "termno": termno,
37 | "resendnotify": 1 if resendnotify else 0,
38 | })
39 | self.add_sign(data)
40 | return self._post('/apiweb/tranx/queryorder', data)
41 |
42 | def refund(self, reqsn, trxamt, trxdate=None, oldtrxid=None, oldbizseq=None, version="01", remark=None):
43 | """
44 | 当面付订单支付-交易退款
45 | https://aipboss.allinpay.com/know/devhelp/home.php?id=208
46 |
47 | :param reqsn: 退款流水号
48 | :param trxamt: 退款金额
49 | :param trxdate: 交易日期
50 | :param oldtrxid: 原交易单号
51 | :param oldbizseq: 原交易商户单号
52 | :param version: 接口版本编号
53 | :param remark: 退款备注
54 | """
55 | if not oldtrxid and not oldbizseq:
56 | raise ValueError("oldtrxid和oldbizseq不能同时为空")
57 |
58 | data = optionaldict({
59 | "cusid": self.cus_id,
60 | "appid": self.app_id,
61 | "version": version,
62 | "trxdate": trxdate,
63 | "reqsn": reqsn,
64 | "oldtrxid": oldtrxid,
65 | "oldbizseq": oldbizseq,
66 | "trxamt": trxamt,
67 | "remark": remark,
68 | })
69 | self.add_sign(data)
70 | return self._post('/voapiweb/unitorder/refund', data)
71 |
72 | def cuspay(self, c, oid=None, amt=None, trxreserve=None):
73 | """
74 | 自带参数的当面付订单接口
75 | https://aipboss.allinpay.com/know/devhelp/home.php?id=292
76 |
77 | :param c: 通联分配的二维码编号
78 | :param oid: 订单编号
79 | :param amt: 交易金额
80 | :param trxreserve: 业务备注信息
81 | """
82 | if not oid and not amt:
83 | raise ValueError("oid和amt不能同时为空")
84 |
85 | data = optionaldict({
86 | "appid": self.app_id,
87 | "c": c,
88 | "oid": oid,
89 | "amt": amt,
90 | "trxreserve": trxreserve
91 | })
92 | self.add_sign(data, random_str_key=None)
93 | return parse.urljoin(self.SYB_API_BASE_URL, '/sappweb/usertrans/cuspay?%s' % parse.urlencode(data))
94 |
--------------------------------------------------------------------------------
/allinpay/client/api/trxfile.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | import datetime
5 |
6 | from optionaldict import optionaldict
7 |
8 | from .base import AllInPayBaseAPI
9 |
10 |
11 | class Trxfile(AllInPayBaseAPI):
12 | """
13 | 对账文件下载接口
14 | """
15 |
16 | def get(self, date):
17 | """
18 | 获取对账单接口
19 | https://aipboss.allinpay.com/know/devhelp/home.php?id=109
20 |
21 | :param date: 交易日期
22 | """
23 | if isinstance(date, datetime.date):
24 | date = date.strftime("%Y%m%d")
25 | data = optionaldict({
26 | "cusid": self.cus_id,
27 | "appid": self.app_id,
28 | "date": date
29 | })
30 | self.add_sign(data)
31 | return self._post("/apiweb/trxfile/get", data, result_processor=lambda x: x['url'])
32 |
33 | def setttrx(self, settdate):
34 | """
35 | 获取结算单接口
36 | https://aipboss.allinpay.com/know/devhelp/home.php?id=422
37 |
38 | :param settdate: 结算日期
39 | """
40 | if isinstance(settdate, datetime.date):
41 | settdate = settdate.strftime("%Y%m%d")
42 | data = optionaldict({
43 | "cusid": self.cus_id,
44 | "appid": self.app_id,
45 | "settdate": settdate
46 | })
47 | self.add_sign(data)
48 | return self._post("/trxfile/setttrx", data, result_processor=lambda x: x['trxlist'])
49 |
--------------------------------------------------------------------------------
/allinpay/client/api/unitorder.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | import json
5 |
6 | import six
7 | from six.moves.urllib import parse
8 | from optionaldict import optionaldict
9 |
10 | from .base import AllInPayBaseAPI
11 |
12 |
13 | class UnitOrder(AllInPayBaseAPI):
14 | """
15 | 网上收银统一下单
16 | """
17 |
18 | def pay(
19 | self, reqsn, trxamt, paytype, acct=None, body=None, notify_url=None, limit_pay=None,
20 | sub_appid=None, goods_tag=None, benefitdetail=None, chnlstoreid=None, subbranch=None,
21 | extendparams=None, cusip=None, idno=None, truename=None, asinfo=None, fqnum=None,
22 | validtime=5, version="11", remark=None
23 | ):
24 | """
25 | 网上收银统一下单-统一支付接口
26 | https://aipboss.allinpay.com/know/devhelp/home.php?id=88
27 |
28 | :param reqsn: 商户交易单号
29 | :param trxamt: 交易金额
30 | :param paytype: 交易方式
31 | :param acct: 支付平台用户标识
32 | :param body: 订单标题
33 | :param notify_url: 交易结果通知地址
34 | :param limit_pay: 支付限制
35 | :param sub_appid: 微信子appid
36 | :param goods_tag: 订单优惠标识
37 | :param benefitdetail: 优惠信息
38 | :param chnlstoreid: 渠道门店编号
39 | :param subbranch: 门店号
40 | :param extendparams: 拓展参数
41 | :param cusip: 终端ip
42 | :param idno: 证件号
43 | :param truename: 付款人真实姓名
44 | :param asinfo: 分账信息
45 | :param fqnum: 花呗分期
46 | :param validtime: 有效时间
47 | :param version: 版本号
48 | :param remark: 备注
49 | """
50 | if extendparams is not None and isinstance(extendparams, six.string_types):
51 | extendparams = json.dumps(extendparams)
52 | data = optionaldict({
53 | "cusid": self.cus_id,
54 | "appid": self.app_id,
55 | "reqsn": reqsn,
56 | "trxamt": trxamt,
57 | "paytype": paytype,
58 | "acct": acct,
59 | "body": body,
60 | "notify_url": notify_url,
61 | "limit_pay": limit_pay,
62 | "sub_appid": sub_appid,
63 | "goods_tag": goods_tag,
64 | "benefitdetail": benefitdetail,
65 | "chnlstoreid": chnlstoreid,
66 | "subbranch": subbranch,
67 | "extendparams": extendparams,
68 | "cusip": cusip,
69 | "idno": idno,
70 | "truename": truename,
71 | "asinfo": asinfo,
72 | "fqnum": fqnum,
73 | "validtime": validtime,
74 | "version": version,
75 | "remark": remark
76 | })
77 | self.add_sign(data)
78 | return self._post("/apiweb/unitorder/pay", data)
79 |
80 | def scanqrpay(
81 | self, reqsn, trxamt, authcode, body=None, limit_pay=None,
82 | goods_tag=None, benefitdetail=None, chnlstoreid=None, subbranch=None,
83 | idno=None, truename=None, asinfo=None, fqnum=None,
84 | version="11", remark=None
85 | ):
86 | """
87 | 网上收银统一统一扫码接口
88 | https://aipboss.allinpay.com/know/devhelp/home.php?id=88
89 |
90 | :param reqsn: 商户交易单号
91 | :param trxamt: 交易金额
92 | :param authcode: 支付授权码
93 | :param body: 订单标题
94 | :param limit_pay: 支付限制
95 | :param goods_tag: 订单优惠标识
96 | :param benefitdetail: 优惠信息
97 | :param chnlstoreid: 渠道门店编号
98 | :param subbranch: 门店号
99 | :param idno: 证件号
100 | :param truename: 付款人真实姓名
101 | :param asinfo: 分账信息
102 | :param fqnum: 花呗分期
103 | :param version: 版本号
104 | :param remark: 备注
105 | """
106 | data = optionaldict({
107 | "cusid": self.cus_id,
108 | "appid": self.app_id,
109 | "reqsn": reqsn,
110 | "trxamt": trxamt,
111 | "authcode": authcode,
112 | "body": body,
113 | "limit_pay": limit_pay,
114 | "goods_tag": goods_tag,
115 | "benefitdetail": benefitdetail,
116 | "chnlstoreid": chnlstoreid,
117 | "subbranch": subbranch,
118 | "idno": idno,
119 | "truename": truename,
120 | "asinfo": asinfo,
121 | "fqnum": fqnum,
122 | "version": version,
123 | "remark": remark
124 | })
125 | self.add_sign(data)
126 | return self._post("/apiweb/unitorder/scanqrpay", data)
127 |
128 | def cancel(self, reqsn, trxamt, oldtrxid=None, oldreqsn=None, version="12"):
129 | """
130 | 网上收银统一下单 - 交易撤销
131 | https://aipboss.allinpay.com/know/devhelp/home.php?id=91
132 | H5收银台 - 交易撤销
133 | https://aipboss.allinpay.com/know/devhelp/home.php?id=315
134 | 手机支付控件 - 交易撤销
135 | https://aipboss.allinpay.com/know/devhelp/home.php?id=393
136 |
137 | :param reqsn: 商户退款交易单号
138 | :param trxamt: 交易金额
139 | :param oldtrxid: 原交易流水
140 | :param oldreqsn: 原交易单号
141 | :param version: 版本号
142 | """
143 | if not oldreqsn and not oldtrxid:
144 | raise ValueError("oldtrxid和oldbizseq不能同时为空")
145 |
146 | data = optionaldict({
147 | "cusid": self.cus_id,
148 | "appid": self.app_id,
149 | "reqsn": reqsn,
150 | "trxamt": trxamt,
151 | "oldtrxid": oldtrxid,
152 | "oldreqsn": oldreqsn,
153 | "version": version
154 | })
155 | self.add_sign(data)
156 | return self._post("/apiweb/unitorder/cancel", data)
157 |
158 | def refund(self, reqsn, trxamt, oldtrxid=None, oldreqsn=None, version="12", remark=None):
159 | """
160 | 网上收银统一下单 - 交易退款
161 | https://aipboss.allinpay.com/know/devhelp/home.php?id=92
162 | H5收银台 - 交易退款
163 | https://aipboss.allinpay.com/know/devhelp/home.php?id=314
164 | 手机支付控件 - 交易退款
165 | https://aipboss.allinpay.com/know/devhelp/home.php?id=394
166 |
167 | :param reqsn: 商户退款交易单号
168 | :param trxamt: 交易金额
169 | :param oldtrxid: 原交易流水
170 | :param oldreqsn: 原交易单号
171 | :param version: 版本号
172 | :param remark: 备注
173 | """
174 | if not oldreqsn and not oldtrxid:
175 | raise ValueError("oldtrxid和oldbizseq不能同时为空")
176 |
177 | data = optionaldict({
178 | "cusid": self.cus_id,
179 | "appid": self.app_id,
180 | "reqsn": reqsn,
181 | "trxamt": trxamt,
182 | "oldtrxid": oldtrxid,
183 | "oldreqsn": oldreqsn,
184 | "remark": remark,
185 | "version": version
186 | })
187 | self.add_sign(data)
188 | return self._post("/apiweb/unitorder/refund", data)
189 |
190 | def query(self, reqsn, trxid, version="12"):
191 | """
192 | 网上收银统一下单 - 交易查询
193 | https://aipboss.allinpay.com/know/devhelp/home.php?id=93
194 | H5收银台 - 交易查询
195 | https://aipboss.allinpay.com/know/devhelp/home.php?id=314
196 | 手机支付控件 - 交易查询
197 | https://aipboss.allinpay.com/know/devhelp/home.php?id=395
198 |
199 | :param reqsn: 商户退款交易单号
200 | :param trxid: 平台交易流水
201 | :param version: 版本号
202 | """
203 | if not reqsn and not trxid:
204 | raise ValueError("trxid和reqsn不能同时为空")
205 |
206 | data = optionaldict({
207 | "cusid": self.cus_id,
208 | "appid": self.app_id,
209 | "reqsn": reqsn,
210 | "trxid": trxid,
211 | "version": version
212 | })
213 | self.add_sign(data)
214 | return self._post("/apiweb/unitorder/query", data)
215 |
216 | def authcodetouserid(self, authcode, authtype, sub_appid=None, version="12"):
217 | """
218 | 网上收银统一下单 - 根据授权码(付款码)获取用户ID
219 | https://aipboss.allinpay.com/know/devhelp/home.php?id=373
220 |
221 | :param authcode: 授权码(付款码)
222 | :param authtype: 授权码类型
223 | :param sub_appid: 微信支付appid
224 | :param version: 版本号
225 | """
226 | data = optionaldict({
227 | "cusid": self.cus_id,
228 | "appid": self.app_id,
229 | "authcode": authcode,
230 | "authtype": authtype,
231 | "sub_appid": sub_appid,
232 | "version": version
233 | })
234 | self.add_sign(data)
235 | return self._post("/apiweb/unitorder/query", data)
236 |
237 | def wxfacepayinfo(self, storeid, storename, subappid, rawdata, deviceid=None, attach=None, version="12"):
238 | """
239 | 网上收银统一下单 - 根据授权码(付款码)获取用户ID
240 | https://aipboss.allinpay.com/know/devhelp/home.php?id=406
241 |
242 | :param storeid: 门店编号
243 | :param storename: 门店名称
244 | :param subappid: 微信支付appid
245 | :param rawdata: 初始化数据。由微信人脸SDK的接口返回。
246 | :param deviceid: 终端设备编号
247 | :param attach: 附加字段
248 | :param version: 版本号
249 | :return:
250 | """
251 | if attach is not None and isinstance(attach, six.string_types):
252 | attach = json.dumps(attach)
253 | data = optionaldict({
254 | "cusid": self.cus_id,
255 | "appid": self.app_id,
256 | "storeid": storeid,
257 | "storename": storename,
258 | "subappid": subappid,
259 | "rawdata": rawdata,
260 | "deviceid": deviceid,
261 | "attach": attach,
262 | "version": version
263 | })
264 | self.add_sign(data)
265 | return self._post("/apiweb/unitorder/query", data)
266 |
267 | def h5unionpay(self, reqsn, trxamt, returl, notify_url, body, charset='utf-8',
268 | version="12", remark=None, validtime=5, limit_pay=None, asinfo=None):
269 | """
270 | H5收银台-订单提交接口
271 | https://aipboss.allinpay.com/know/devhelp/home.php?id=313
272 |
273 | :param reqsn: 商户唯一订单号
274 | :param trxamt: 付款金额(单位分)
275 | :param returl: 页面跳转同步通知页面路径
276 | :param notify_url: 服务器异步通知页面路径
277 | :param body: 订单标题
278 | :param charset: 参数字符编码集
279 | :param version: 版本号
280 | :param remark: 订单备注信息
281 | :param validtime: 有效时间
282 | :param limit_pay: 支付限制
283 | :param asinfo: 分账信息
284 | """
285 | data = optionaldict({
286 | "cusid": self.cus_id,
287 | "appid": self.app_id,
288 | "trxamt": trxamt,
289 | "reqsn": reqsn,
290 | "returl": returl,
291 | "notify_url": notify_url,
292 | "body": body,
293 | "charset": charset,
294 | "version": version,
295 | "remark": remark,
296 | "validtime": validtime,
297 | "limit_pay": limit_pay,
298 | "asinfo": asinfo,
299 | })
300 | self.add_sign(data)
301 | return parse.urljoin(
302 | self.SYB_API_BASE_URL, '/apiweb/h5unionpay/unionorder?%s' % parse.urlencode(data, encoding=charset)
303 | )
304 |
--------------------------------------------------------------------------------
/allinpay/client/api/verify.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | import datetime
5 |
6 | from optionaldict import optionaldict
7 |
8 | from .base import AllInPayBaseAPI
9 |
10 |
11 | class Verify(AllInPayBaseAPI):
12 | """
13 | 银行账户要素认证
14 | """
15 | def _bankverify(self, num, reqsn, cardno, name, idno=None, phone=None, version='11'):
16 | data = optionaldict({
17 | "cusid": self.cus_id,
18 | "appid": self.app_id,
19 | "version": version,
20 | "reqtime": datetime.datetime.now().strftime(""),
21 | "reqsn": reqsn,
22 | "cardno": cardno,
23 | "name": name,
24 | "idno": idno,
25 | "phone": phone
26 | })
27 | self.add_sign(data)
28 | return self._post("/apiweb/verify/bankverify%d" % num, data, result_processor=lambda x: x['validid'])
29 |
30 | def bankverify2(self, reqsn, cardno, name, version='11'):
31 | """
32 | 银行账户二要素验证
33 | https://aipboss.allinpay.com/know/devhelp/home.php?id=253
34 |
35 | :param reqsn: 请求流水
36 | :param cardno: 银行卡号
37 | :param name: 户名
38 | :param version: 版本号
39 | """
40 | return self._bankverify(2, reqsn, cardno, name, version=version)
41 |
42 | def bankverify3(self, reqsn, cardno, name, idno, version='11'):
43 | """
44 | 银行账户三要素验证
45 | https://aipboss.allinpay.com/know/devhelp/home.php?id=254
46 |
47 | :param reqsn: 请求流水
48 | :param cardno: 银行卡号
49 | :param name: 户名
50 | :param idno: 身份证号
51 | :param version: 版本号
52 | """
53 | return self._bankverify(3, reqsn, cardno, name, idno, version=version)
54 |
55 | def bankverify4(self, reqsn, cardno, name, idno, phone, version='11'):
56 | """
57 | 银行账户四要素验证
58 | https://aipboss.allinpay.com/know/devhelp/home.php?id=255
59 |
60 | :param reqsn: 请求流水
61 | :param cardno: 银行卡号
62 | :param name: 户名
63 | :param idno: 身份证号
64 | :param phone: 手机号码
65 | :param version: 版本号
66 | """
67 | return self._bankverify(4, reqsn, cardno, name, idno, phone, version=version)
68 |
--------------------------------------------------------------------------------
/allinpay/client/base.py:
--------------------------------------------------------------------------------
1 | # encoding: utf-8
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | import inspect
5 | import logging
6 | import requests
7 | from six.moves.urllib.parse import urljoin, urlencode
8 |
9 | from .api.base import AllInPayBaseAPI
10 | from ..core.exceptions import AllInPayClientException
11 | from ..core.utils import json_loads
12 |
13 |
14 | logger = logging.getLogger(__name__)
15 |
16 |
17 | def _is_api_endpoint(obj):
18 | return isinstance(obj, AllInPayBaseAPI)
19 |
20 |
21 | class BaseClient(object):
22 |
23 | _http = requests.Session()
24 |
25 | API_BASE_URL = 'https://vsp.allinpay.com/'
26 | SYB_API_BASE_URL = 'https://syb.allinpay.com/'
27 |
28 | def __new__(cls, *args, **kwargs):
29 | self = super(BaseClient, cls).__new__(cls)
30 | api_endpoints = inspect.getmembers(self, _is_api_endpoint)
31 | for name, api in api_endpoints:
32 | api_cls = type(api)
33 | api = api_cls(self)
34 | setattr(self, name, api)
35 | return self
36 |
37 | def __init__(self, timeout=None):
38 | self.timeout = timeout
39 |
40 | def _request(self, method, url_or_endpoint, **kwargs):
41 | if not url_or_endpoint.startswith(('http://', 'https://')):
42 | api_base_url = kwargs.pop('api_base_url', self.API_BASE_URL)
43 | url = urljoin(api_base_url, url_or_endpoint)
44 | else:
45 | url = url_or_endpoint
46 |
47 | if 'params' not in kwargs:
48 | kwargs['params'] = {}
49 | if isinstance(kwargs.get('data', ''), dict):
50 | kwargs['data'] = urlencode(kwargs['data'])
51 | if 'headers' not in kwargs:
52 | kwargs['headers'] = {}
53 | kwargs['headers']['Content-Type'] = 'application/x-www-form-urlencoded'
54 |
55 | kwargs['timeout'] = kwargs.get('timeout', self.timeout)
56 | result_processor = kwargs.pop('result_processor', None)
57 | res = self._http.request(
58 | method=method,
59 | url=url,
60 | **kwargs
61 | )
62 | try:
63 | res.raise_for_status()
64 | except requests.RequestException as reqe:
65 | logger.error("\n【请求地址】: %s\n【请求参数】:%s \n%s\n【异常信息】:%s",
66 | url, kwargs.get('params', ''), kwargs.get('data', ''), reqe)
67 | raise AllInPayClientException(
68 | errcode=None,
69 | errmsg=None,
70 | client=self,
71 | request=reqe.request,
72 | response=reqe.response
73 | )
74 |
75 | result = self._handle_result(res, method, url, result_processor, **kwargs)
76 |
77 | logger.debug("\n【请求地址】: %s\n【请求参数】:%s \n%s\n【响应数据】:%s",
78 | url, kwargs.get('params', ''), kwargs.get('data', ''), result)
79 | return result
80 |
81 | def _decode_result(self, res):
82 | try:
83 | result = json_loads(res.content.decode('utf-8', 'ignore'), strict=False)
84 | except (TypeError, ValueError):
85 | # Return origin response object if we can not decode it as JSON
86 | logger.debug('Can not decode response as JSON', exc_info=True)
87 | return res
88 | return result
89 |
90 | def _handle_result(self, res, method=None, url=None, result_processor=None, **kwargs):
91 | if not isinstance(res, dict):
92 | # Dirty hack around asyncio based AsyncWeChatClient
93 | result = self._decode_result(res)
94 | else:
95 | result = res
96 |
97 | if not isinstance(result, dict):
98 | return result
99 | if 'sign' in result:
100 | try:
101 | self.check_sign(result)
102 | except AllInPayClientException as e:
103 | logger.error("%s\n【请求地址】: %s\n【请求参数】:%s \n%s\n【错误信息】:%s",
104 | e, url, kwargs.get('params', ''), kwargs.get('data', ''), result)
105 | raise AllInPayClientException(
106 | e.errcode,
107 | e.errmsg,
108 | client=self,
109 | request=res.request,
110 | response=res
111 | )
112 |
113 | if 'retcode' in result and result['retcode'] != 'SUCCESS':
114 | retcode = result['retcode']
115 | retmsg = result.get('retmsg', retcode)
116 |
117 | logger.error("\n【请求地址】: %s\n【请求参数】:%s \n%s\n【错误信息】:%s",
118 | url, kwargs.get('params', ''), kwargs.get('data', ''), result)
119 | raise AllInPayClientException(
120 | retcode,
121 | retmsg,
122 | client=self,
123 | request=res.request,
124 | response=res
125 | )
126 | if 'trxstatus' in result and result['trxstatus'] != '0000':
127 | trxstatus = result['trxstatus']
128 | errmsg = result.get('errmsg', trxstatus)
129 |
130 | logger.error("\n【请求地址】: %s\n【请求参数】:%s \n%s\n【错误信息】:%s",
131 | url, kwargs.get('params', ''), kwargs.get('data', ''), result)
132 | raise AllInPayClientException(
133 | trxstatus,
134 | errmsg,
135 | client=self,
136 | request=res.request,
137 | response=res
138 | )
139 |
140 | return result if not result_processor else result_processor(result)
141 |
142 | def _handle_pre_request(self, method, uri, kwargs):
143 | return method, uri, kwargs
144 |
145 | def _handle_request_except(self, e, func, *args, **kwargs):
146 | raise e
147 |
148 | def check_sign(self, data, sign_key="sign"):
149 | raise NotImplementedError
150 |
151 | def request(self, method, uri, **kwargs):
152 | method, uri_with_access_token, kwargs = self._handle_pre_request(method, uri, kwargs)
153 | try:
154 | return self._request(method, uri_with_access_token, **kwargs)
155 | except AllInPayClientException as e:
156 | return self._handle_request_except(e, self.request, method, uri, **kwargs)
157 |
158 | def get(self, uri, params=None, **kwargs):
159 | """
160 | get 接口请求
161 |
162 | :param uri: 请求url
163 | :param params: get 参数(dict 格式)
164 | """
165 | if params is not None:
166 | kwargs['params'] = params
167 | return self.request('GET', uri, **kwargs)
168 |
169 | def post(self, uri, data=None, params=None, **kwargs):
170 | """
171 | post 接口请求
172 |
173 | :param uri: 请求url
174 | :param data: post 数据
175 | :param params: post接口中url问号后参数(dict 格式)
176 | """
177 | if data is not None:
178 | kwargs['data'] = data
179 | if params is not None:
180 | kwargs['params'] = params
181 | return self.request('POST', uri, **kwargs)
182 |
--------------------------------------------------------------------------------
/allinpay/core/__init__.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import absolute_import, unicode_literals
3 |
--------------------------------------------------------------------------------
/allinpay/core/exceptions.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | import six
5 |
6 | from .utils import to_binary, to_text
7 |
8 |
9 | class AllInPayException(Exception):
10 |
11 | def __init__(self, errcode, errmsg):
12 | """
13 | :param errcode: Error code
14 | :param errmsg: Error message
15 | """
16 | self.errcode = errcode
17 | self.errmsg = errmsg
18 |
19 | def __str__(self):
20 | _repr = 'Error code: {code}, message: {msg}'.format(
21 | code=self.errcode,
22 | msg=self.errmsg
23 | )
24 |
25 | if six.PY2:
26 | return to_binary(_repr)
27 | else:
28 | return to_text(_repr)
29 |
30 | def __repr__(self):
31 | _repr = '{klass}({code}, {msg})'.format(
32 | klass=self.__class__.__name__,
33 | code=self.errcode,
34 | msg=self.errmsg
35 | )
36 | if six.PY2:
37 | return to_binary(_repr)
38 | else:
39 | return to_text(_repr)
40 |
41 |
42 | class AllInPayClientException(AllInPayException):
43 | """WeChat API client exception class"""
44 | def __init__(self, errcode, errmsg, client=None,
45 | request=None, response=None):
46 | super(AllInPayClientException, self).__init__(errcode, errmsg)
47 | self.client = client
48 | self.request = request
49 | self.response = response
50 |
51 |
52 | class InvalidSignatureException(AllInPayException):
53 | """Invalid signature exception class"""
54 |
55 | def __init__(self, errcode=-40001, errmsg='Invalid signature'):
56 | super(InvalidSignatureException, self).__init__(errcode, errmsg)
57 |
58 |
59 | class InvalidCorpIdOrSuiteKeyException(AllInPayException):
60 | """Invalid app_id exception class"""
61 |
62 | def __init__(self, errcode=-40005, errmsg='Invalid CorpIdOrSuiteKey'):
63 | super(InvalidCorpIdOrSuiteKeyException, self).__init__(errcode, errmsg)
64 |
--------------------------------------------------------------------------------
/allinpay/core/utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import absolute_import, unicode_literals
3 |
4 | import base64
5 | import copy
6 | import hashlib
7 | import json
8 | import random
9 | import string
10 |
11 | import six
12 |
13 |
14 | class ObjectDict(dict):
15 | """Makes a dictionary behave like an object, with attribute-style access.
16 | """
17 |
18 | def __getattr__(self, key):
19 | if key in self:
20 | return self[key]
21 | return None
22 |
23 | def __setattr__(self, key, value):
24 | self[key] = value
25 |
26 |
27 | class AllInPaySigner(object):
28 | """AllInPay data signer"""
29 |
30 | def __init__(self, delimiter=b'', key=None):
31 | self._key = key
32 | self._data = []
33 | self._delimiter = to_binary(delimiter)
34 |
35 | def add_data(self, *args):
36 | """Add data to signer"""
37 | for data in args:
38 | self._data.append(to_binary(data))
39 |
40 | @property
41 | def signature(self):
42 | """Get data signature"""
43 | raise NotImplementedError
44 |
45 | def verify(self, sign):
46 | """check sign"""
47 | return self.signature == sign
48 |
49 |
50 | class AllInPayMd5Signer(AllInPaySigner):
51 |
52 | @classmethod
53 | def get_public_key(cls, key):
54 | return "key=%s" % key
55 |
56 | @classmethod
57 | def get_private_key(cls, key):
58 | return "key=%s" % key
59 |
60 | @property
61 | def signature(self):
62 | data = copy.copy(self._data)
63 | if self._key:
64 | data.append(to_binary(self._key))
65 | data.sort()
66 | str_to_sign = self._delimiter.join(data)
67 | return hashlib.md5(str_to_sign).hexdigest().lower()
68 |
69 | def verify(self, sign):
70 | return self.signature == sign
71 |
72 |
73 | class AllInPayRsaSigner(AllInPaySigner):
74 |
75 | @classmethod
76 | def get_public_key(cls, key):
77 | from Crypto.PublicKey import RSA
78 | return RSA.import_key(base64.b64decode(key))
79 |
80 | @classmethod
81 | def get_private_key(cls, key):
82 | from Crypto.PublicKey import RSA
83 | return RSA.import_key(base64.b64decode(key))
84 |
85 | def get_str_to_sign(self):
86 | data = copy.copy(self._data)
87 | data.sort()
88 | return self._delimiter.join(data)
89 |
90 | def get_digest(self):
91 | from Crypto.Hash import SHA1
92 | return SHA1.new(self.get_str_to_sign())
93 |
94 | @property
95 | def signature(self):
96 | from Crypto.Signature import pkcs1_15
97 | return to_text(base64.b64encode(pkcs1_15.new(self._key).sign(self.get_digest())))
98 |
99 | def verify(self, sign):
100 | from Crypto.Signature import pkcs1_15
101 | try:
102 | pkcs1_15.new(self._key).verify(self.get_digest(), base64.b64decode(sign))
103 | return True
104 | except (ValueError, TypeError):
105 | return False
106 |
107 |
108 | class AllInPaySm2Signer(AllInPayRsaSigner):
109 | @classmethod
110 | def get_public_key(cls, key):
111 | return base64.b64decode(key)
112 |
113 | @classmethod
114 | def get_private_key(cls, key):
115 | return base64.b64decode(key)
116 |
117 | @property
118 | def signature(self):
119 | raise RuntimeError("暂不支持")
120 |
121 | def verify(self, sign):
122 | raise RuntimeError("暂不支持")
123 |
124 |
125 | def to_text(value, encoding='utf-8'):
126 | """Convert value to unicode, default encoding is utf-8
127 |
128 | :param value: Value to be converted
129 | :param encoding: Desired encoding
130 | """
131 | if value is None:
132 | return ''
133 | if isinstance(value, six.text_type):
134 | return value
135 | if isinstance(value, six.binary_type):
136 | return value.decode(encoding)
137 | return six.text_type(value)
138 |
139 |
140 | def to_binary(value, encoding='utf-8'):
141 | """Convert value to binary string, default encoding is utf-8
142 |
143 | :param value: Value to be converted
144 | :param encoding: Desired encoding
145 | """
146 | if value is None:
147 | return b''
148 | if isinstance(value, six.binary_type):
149 | return value
150 | if isinstance(value, six.text_type):
151 | return value.encode(encoding)
152 | return to_text(value).encode(encoding)
153 |
154 |
155 | def random_string(length=16):
156 | rule = string.ascii_letters + string.digits
157 | rand_list = random.sample(rule, length)
158 | return ''.join(rand_list)
159 |
160 |
161 | def byte2int(c):
162 | if six.PY2:
163 | return ord(c)
164 | return c
165 |
166 |
167 | def json_loads(s, object_hook=ObjectDict, **kwargs):
168 | return json.loads(s, object_hook=object_hook, **kwargs)
169 |
--------------------------------------------------------------------------------
/dev-requirements.txt:
--------------------------------------------------------------------------------
1 | -r requirements.txt
2 | attrs<21.1.0; python_version < '3.5'
3 | pytest
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line.
5 | SPHINXOPTS =
6 | SPHINXBUILD = sphinx-build
7 | SPHINXPROJ = pyallinpay
8 | SOURCEDIR = .
9 | BUILDDIR = _build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
21 |
--------------------------------------------------------------------------------
/docs/changelog.rst:
--------------------------------------------------------------------------------
1 | Changelog
2 | ================
3 |
4 | Version 1.2.0
5 | ------------------
6 | + 支持ras加密方式
7 |
8 | Version 1.1.8
9 | ------------------
10 | + fix to_text 空值判断导致 sign 计算错误
11 |
12 | Version 1.1.6
13 | ------------------
14 | + 获取结算单接口
15 | + 返回内容签名验证失败增加error log
16 | + sign验证不区分大小写
17 | + 部分接口增加文档链接
18 | + 对账文件下载接口/协同收银/银行账户要素认证 增加到client
19 |
20 | Version 1.1.5
21 | ------------------
22 | + H5收银台 增加charset参数
23 |
24 | Version 1.1.3
25 | ------------------
26 | + 自带参数的当面付订单接口
27 |
28 | Version 1.1.2
29 | ------------------
30 | + js支付返回url
31 | + 签名认证转小写
32 |
33 | Version 1.1.0
34 | ------------------
35 |
36 | + 对账文件下载接口
37 | + 协同收银
38 | + 银行账户要素认证
39 | + 终端订单支付
40 | + 当面付订单支付
41 | + 网关支付
42 | + 网上收银统一下单
43 | + 快捷支付
44 | + H5收银台
45 | + 网上收银预消费
46 |
--------------------------------------------------------------------------------
/docs/client/api/gateway.rst:
--------------------------------------------------------------------------------
1 | 网关支付
2 | ===================
3 |
4 | .. module:: allinpay.client.api
5 |
6 | .. autoclass:: Gateway
7 | :members:
8 | :inherited-members:
9 |
10 |
--------------------------------------------------------------------------------
/docs/client/api/posol.rst:
--------------------------------------------------------------------------------
1 | 协同收银
2 | ===================
3 |
4 | .. module:: allinpay.client.api
5 |
6 | .. autoclass:: Posol
7 | :members:
8 | :inherited-members:
9 |
10 |
--------------------------------------------------------------------------------
/docs/client/api/prescanpay.rst:
--------------------------------------------------------------------------------
1 | 网上收银预消费
2 | ===================
3 |
4 | .. module:: allinpay.client.api
5 |
6 | .. autoclass:: PreScanPay
7 | :members:
8 | :inherited-members:
9 |
10 |
--------------------------------------------------------------------------------
/docs/client/api/qpay.rst:
--------------------------------------------------------------------------------
1 | 快捷支付
2 | ===================
3 |
4 | .. module:: allinpay.client.api
5 |
6 | .. autoclass:: QPay
7 | :members:
8 | :inherited-members:
9 |
10 |
--------------------------------------------------------------------------------
/docs/client/api/tranx.rst:
--------------------------------------------------------------------------------
1 | 终端订单支付, 当面付订单支付
2 | ===============================
3 |
4 | .. module:: allinpay.client.api
5 |
6 | .. autoclass:: Tranx
7 | :members:
8 | :inherited-members:
9 |
10 |
--------------------------------------------------------------------------------
/docs/client/api/trxfile.rst:
--------------------------------------------------------------------------------
1 | 对账文件下载接口
2 | ===================
3 |
4 | .. module:: allinpay.client.api
5 |
6 | .. autoclass:: Trxfile
7 | :members:
8 | :inherited-members:
9 |
10 |
--------------------------------------------------------------------------------
/docs/client/api/unitorder.rst:
--------------------------------------------------------------------------------
1 | 网上收银统一下单
2 | ===================
3 |
4 | .. module:: allinpay.client.api
5 |
6 | .. autoclass:: UnitOrder
7 | :members:
8 | :inherited-members:
9 |
10 |
--------------------------------------------------------------------------------
/docs/client/api/verify.rst:
--------------------------------------------------------------------------------
1 | 银行账户要素认证
2 | ===================
3 |
4 | .. module:: allinpay.client.api
5 |
6 | .. autoclass:: Verify
7 | :members:
8 | :inherited-members:
9 |
10 |
--------------------------------------------------------------------------------
/docs/client/index.rst:
--------------------------------------------------------------------------------
1 | 通联支付接口
2 | ===========================================
3 |
4 | .. module:: allinpay.client
5 |
6 | .. autoclass:: AllInPayClient
7 | :members:
8 | :inherited-members:
9 |
10 | .. autoclass:: AllInPayTestClient
11 | :members:
12 | :inherited-members:
13 |
14 | `AllInPayClient` 基本使用方法::
15 |
16 | from allinpay import AllInPayClient, AllInPayTestClient
17 |
18 | client = AllInPayClient('00000003', '990440148166000', 'a0ea3fa20dbd7bb4d5abf1d59d63bae8') # 生产环境
19 | test_client = AllInPayTestClient('00000051', '990581007426001', 'allinpay888') # 测试环境
20 |
21 | info = client.unitorder.pay('1234567890', 1, 'W01')
22 | info = test_client.unitorder.pay('1234567890', 1, 'W01')
23 |
24 |
25 | .. toctree::
26 | :maxdepth: 2
27 | :glob:
28 |
29 | api/*
30 |
31 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | #
3 | # Configuration file for the Sphinx documentation builder.
4 | #
5 | # This file does only contain a selection of the most common options. For a
6 | # full list see the documentation:
7 | # http://www.sphinx-doc.org/en/master/config
8 |
9 | import sphinx_rtd_theme
10 |
11 | # -- Path setup --------------------------------------------------------------
12 |
13 | # If extensions (or modules to document with autodoc) are in another directory,
14 | # add these directories to sys.path here. If the directory is relative to the
15 | # documentation root, use os.path.abspath to make it absolute, like shown here.
16 | #
17 | import os
18 | import sys
19 |
20 | sys.path.insert(0, os.path.abspath('..'))
21 |
22 | import allinpay # NOQA
23 |
24 |
25 | # -- Project information -----------------------------------------------------
26 |
27 | project = 'pyallinpay'
28 | copyright = '2018, 007gzs'
29 | author = '007gzs'
30 |
31 | # The short X.Y version
32 | version = allinpay.__version__
33 | # The full version, including alpha/beta/rc tags
34 | release = allinpay.__version__
35 |
36 |
37 | # -- General configuration ---------------------------------------------------
38 |
39 | # If your documentation needs a minimal Sphinx version, state it here.
40 | #
41 | # needs_sphinx = '1.0'
42 |
43 | # Add any Sphinx extension module names here, as strings. They can be
44 | # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
45 | # ones.
46 | extensions = [
47 | 'sphinx.ext.autodoc',
48 | 'sphinx.ext.doctest',
49 | 'sphinx.ext.intersphinx',
50 | 'sphinx.ext.todo',
51 | 'sphinx.ext.coverage',
52 | 'sphinx.ext.mathjax',
53 | 'sphinx.ext.ifconfig',
54 | 'sphinx.ext.viewcode',
55 | 'sphinx.ext.githubpages',
56 | ]
57 |
58 | # Add any paths that contain templates here, relative to this directory.
59 | templates_path = ['_templates']
60 |
61 | # The suffix(es) of source filenames.
62 | # You can specify multiple suffix as a list of string:
63 | #
64 | # source_suffix = ['.rst', '.md']
65 | source_suffix = '.rst'
66 |
67 | # The master toctree document.
68 | master_doc = 'index'
69 |
70 | # The language for content autogenerated by Sphinx. Refer to documentation
71 | # for a list of supported languages.
72 | #
73 | # This is also used if you do content translation via gettext catalogs.
74 | # Usually you set "language" from the command line for these cases.
75 | language = 'zh_cn'
76 |
77 | # List of patterns, relative to source directory, that match files and
78 | # directories to ignore when looking for source files.
79 | # This pattern also affects html_static_path and html_extra_path .
80 | exclude_patterns = []
81 |
82 | # The name of the Pygments (syntax highlighting) style to use.
83 | pygments_style = 'sphinx'
84 |
85 |
86 | # -- Options for HTML output -------------------------------------------------
87 |
88 | # The theme to use for HTML and HTML Help pages. See the documentation for
89 | # a list of builtin themes.
90 | #
91 | # html_theme = 'alabaster'
92 |
93 | html_theme = "sphinx_rtd_theme"
94 | html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
95 |
96 | # Theme options are theme-specific and customize the look and feel of a theme
97 | # further. For a list of options available for each theme, see the
98 | # documentation.
99 | #
100 | # html_theme_options = {}
101 |
102 | # Add any paths that contain custom static files (such as style sheets) here,
103 | # relative to this directory. They are copied after the builtin static files,
104 | # so a file named "default.css" will overwrite the builtin "default.css".
105 | html_static_path = ['_static']
106 |
107 | # Custom sidebar templates, must be a dictionary that maps document names
108 | # to template names.
109 | #
110 | # The default sidebars (for documents that don't match any pattern) are
111 | # defined by theme itself. Builtin themes are using these templates by
112 | # default: ``['localtoc.html', 'relations.html', 'sourcelink.html',
113 | # 'searchbox.html']``.
114 | #
115 | # html_sidebars = {}
116 |
117 |
118 | # -- Options for HTMLHelp output ---------------------------------------------
119 |
120 | # Output file base name for HTML help builder.
121 | htmlhelp_basename = 'pyallinpay-doc'
122 |
123 |
124 | # -- Options for LaTeX output ------------------------------------------------
125 |
126 | latex_elements = {
127 | # The paper size ('letterpaper' or 'a4paper').
128 | #
129 | # 'papersize': 'letterpaper',
130 |
131 | # The font size ('10pt', '11pt' or '12pt').
132 | #
133 | # 'pointsize': '10pt',
134 |
135 | # Additional stuff for the LaTeX preamble.
136 | #
137 | # 'preamble': '',
138 |
139 | # Latex figure (float) alignment
140 | #
141 | # 'figure_align': 'htbp',
142 | }
143 |
144 | # Grouping the document tree into LaTeX files. List of tuples
145 | # (source start file, target name, title,
146 | # author, documentclass [howto, manual, or own class]).
147 | latex_documents = [
148 | (master_doc, 'pyallinpay.tex', 'pyallinpay Documentation',
149 | '007gzs', 'manual'),
150 | ]
151 |
152 |
153 | # -- Options for manual page output ------------------------------------------
154 |
155 | # One entry per manual page. List of tuples
156 | # (source start file, name, description, authors, manual section).
157 | man_pages = [
158 | (master_doc, 'pyallinpay', 'pyallinpay Documentation',
159 | [author], 1)
160 | ]
161 |
162 |
163 | # -- Options for Texinfo output ----------------------------------------------
164 |
165 | # Grouping the document tree into Texinfo files. List of tuples
166 | # (source start file, target name, title, author,
167 | # dir menu entry, description, category)
168 | texinfo_documents = [
169 | (master_doc, 'pyallinpay', 'pyallinpay Documentation',
170 | author, 'pyallinpay', 'One line description of project.',
171 | 'Miscellaneous'),
172 | ]
173 |
174 |
175 | # -- Extension configuration -------------------------------------------------
176 |
177 | # -- Options for intersphinx extension ---------------------------------------
178 |
179 | # Example configuration for intersphinx: refer to the Python standard library.
180 | intersphinx_mapping = {'https://docs.python.org/': None}
181 |
182 | # -- Options for todo extension ----------------------------------------------
183 |
184 | # If true, `todo` and `todoList` produce output, else they produce nothing.
185 | todo_include_todos = True
186 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 |
2 | PyAllInPay 使用文档
3 | ========================================
4 |
5 | PyAllInPay 是通联支付 Python SDK。
6 |
7 | 快速入门
8 | -------------
9 |
10 | .. toctree::
11 | :maxdepth: 2
12 |
13 | install
14 |
15 |
16 | 开始使用
17 | --------------------
18 | 建议在使用前先阅读 `通联支付文档 `_
19 |
20 | .. toctree::
21 | :glob:
22 | :maxdepth: 2
23 |
24 | client/index
25 |
26 | 调用示例::
27 |
28 | from allinpay import AllInPayClient, AllInPayTestClient
29 |
30 | client = AllInPayClient('00000003', '990440148166000', 'a0ea3fa20dbd7bb4d5abf1d59d63bae8') # 生产环境
31 | test_client = AllInPayTestClient('00000051', '990581007426001', 'allinpay888') # 测试环境
32 |
33 | info = client.unitorder.pay('1234567890', 1, 'W01')
34 | info = test_client.unitorder.pay('1234567890', 1, 'W01')
35 |
36 |
37 | Changelogs
38 | ---------------
39 |
40 | .. toctree::
41 | :maxdepth: 1
42 |
43 | changelog
44 |
45 |
--------------------------------------------------------------------------------
/docs/install.rst:
--------------------------------------------------------------------------------
1 | 安装与升级
2 | ==========
3 |
4 | 目前 PyAllInPay 支持的 Python 环境有 2.7, 3.4, 3.5, 3.6, 3.7 和 pypy。
5 |
6 | 为了简化安装过程,推荐使用 pip 进行安装
7 |
8 | .. code-block:: bash
9 |
10 | pip install pyallinpay
11 |
12 | 升级 pyallinpay 到新版本::
13 |
14 | pip install -U pyallinpay
15 |
16 | 如果需要安装 GitHub 上的最新代码::
17 |
18 | pip install https://github.com/007gzs/pyallinpay/archive/master.zip
19 |
20 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | six>=1.8.0
2 | requests>=2.4.3
3 | optionaldict>=0.1.0
4 | pycryptodome>=3
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [flake8]
2 | exclude = .svn,CVS,.bzr,.hg,.git,__pycache,.ropeproject
3 | max-line-length = 120
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | #! /usr/bin/env python
2 | # encoding: utf-8
3 |
4 |
5 | """A setuptools based setup module.
6 |
7 | See:
8 | https://packaging.python.org/en/latest/distributing.html
9 | https://github.com/pypa/sampleproject
10 | """
11 |
12 | # Always prefer setuptools over distutils
13 | from setuptools import setup, find_packages
14 | from setuptools.command.test import test as TestCommand
15 | # To use a consistent encoding
16 | from codecs import open
17 | from os import path
18 | import sys
19 |
20 |
21 | here = path.abspath(path.dirname(__file__))
22 |
23 |
24 | class PyTest(TestCommand):
25 | user_options = [('pytest-args=', 'a', "Arguments to pass to py.test")]
26 |
27 | def initialize_options(self):
28 | TestCommand.initialize_options(self)
29 | self.pytest_args = []
30 |
31 | def finalize_options(self):
32 | TestCommand.finalize_options(self)
33 | self.test_args = []
34 | self.test_suite = True
35 |
36 | def run_tests(self):
37 | import pytest
38 | errno = pytest.main(self.pytest_args)
39 | sys.exit(errno)
40 |
41 |
42 | cmdclass = {}
43 | cmdclass['test'] = PyTest
44 |
45 | # Get the long description from the README file
46 | with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
47 | long_description = f.read()
48 |
49 | with open('requirements.txt') as f:
50 | requirements = [line for line in f.read().splitlines() if line]
51 |
52 | setup(
53 | name='pyallinpay',
54 | version='1.1.10',
55 | keywords='pyallinpay, SDK, 通联支付',
56 | description='AllInPay SDK for Python',
57 | long_description=long_description,
58 | url='https://github.com/007gzs/pyallinpay',
59 | author='007gzs',
60 | author_email='007gzs@sina.com',
61 | license='LGPL v3',
62 | classifiers=[
63 | 'Development Status :: 3 - Alpha',
64 | 'Intended Audience :: Developers',
65 | 'Topic :: Software Development :: Build Tools',
66 | 'License :: OSI Approved :: '
67 | 'GNU Lesser General Public License v3 (LGPLv3)',
68 | 'Programming Language :: Python :: 2',
69 | 'Programming Language :: Python :: 2.7',
70 | 'Programming Language :: Python :: 3',
71 | 'Programming Language :: Python :: 3.4',
72 | 'Programming Language :: Python :: 3.5',
73 | 'Programming Language :: Python :: 3.6',
74 | 'Programming Language :: Python :: 3.7',
75 | ],
76 | packages=find_packages(exclude=('tests', )),
77 | install_requires=requirements,
78 | zip_safe=False,
79 | include_package_data=True,
80 | tests_require=[
81 | 'pytest',
82 | ],
83 | cmdclass=cmdclass,
84 | )
85 |
--------------------------------------------------------------------------------
/tests/test_utils.py:
--------------------------------------------------------------------------------
1 | # -*- coding: utf-8 -*-
2 | from __future__ import absolute_import, unicode_literals
3 | import unittest
4 |
5 | import pytest
6 |
7 | from allinpay.core.utils import ObjectDict, AllInPayMd5Signer, AllInPayRsaSigner
8 |
9 |
10 | class UtilityTestCase(unittest.TestCase):
11 |
12 | def test_object_dict(self):
13 | obj = ObjectDict()
14 | self.assertTrue(obj.xxx is None)
15 | obj.xxx = 1
16 | self.assertEqual(1, obj.xxx)
17 |
18 | def test_md5_signer(self):
19 |
20 | signer = AllInPayMd5Signer(key="1234567890")
21 | signer.add_data('789')
22 | signer.add_data('456')
23 | signer.add_data('123')
24 | signature = signer.signature
25 |
26 | self.assertEqual('83de4f53c5fffe5a7b5bd402c53ba939', signature)
27 |
28 | def test_rsa_signer(self):
29 | private_key = (
30 | "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJgHMGYsspghvP+yCbjLG43CkZuQ3YJyDcmEKxvmgblITfmi"
31 | "TPx2b9Y2iwDT9gnLGExTDm1BL2A8VzMobjaHfiCmTbDctu680MLmpDDkVXmJOqdlXh0tcLjhN4+iDA2KkRqiHxsDpiaKT6MM"
32 | "BuecXQbJtPlVc1XjVhoUlzUgPCrvAgMBAAECgYAV9saYTGbfsdLOF5kYo0dve1JxaO7dFMCcgkV+z2ujKtNmeHtU54DlhZXJ"
33 | "iytQY5Dhc10cjb6xfFDrftuFcfKCaLiy6h5ETR8jyv5He6KH/+X6qkcGTkJBYG1XvyyFO3PxoszQAs0mrLCqq0UItlCDn0G7"
34 | "2MR9/NuvdYabGHSzEQJBAMXB1/DUvBTHHH4LiKDiaREruBb3QtP72JQS1ATVXA2v6xJzGPMWMBGQDvRfPvuCPVmbHENX+lRx"
35 | "MLp39OvIn6kCQQDEzYpPcuHW/7h3TYHYc+T0O6z1VKQT2Mxv92Lj35g1XqV4Oi9xrTj2DtMeV1lMx6n/3icobkCQtuvTI+Ac"
36 | "qfTXAkB6bCz9NwUUK8sUsJktV9xJN/JnrTxetOr3h8xfDaJGCuCQdFY+rj6lsLPBTnFUC+Vk4mQVwJIE0mmjFf22NWW5AkAm"
37 | "sVaRGkAmui41Xoq52MdZ8WWm8lY0BLrlBJlvveU6EPqtcZskWW9KiU2euIO5IcRdpvrB6zNMgHpLD9GfMRcPAkBUWOV/dH13"
38 | "v8V2Y/Fzuag/y5k3/oXi/WQnIxdYbltad2xjmofJ7DbB7MJqiZZD8jlr8PCZPwRNzc5ntDStc959"
39 | )
40 | signer = AllInPayRsaSigner(key=AllInPayRsaSigner.get_private_key(private_key), delimiter=b"&")
41 | signer.add_data('appid=00000051')
42 | signer.add_data('cusid=990581007426001')
43 | signer.add_data('randomstr=82712208')
44 | signer.add_data('signtype=RSA')
45 | signer.add_data('trxid=112094120001088317')
46 | signer.add_data('version=11')
47 | signature = signer.signature
48 | self.assertTrue(signer.verify(signature))
49 |
50 | self.assertEqual(
51 | (
52 | 'ce6EAOj4rhoBMJM5MJCNG4qQ/CVMTWkoRuSGpSzRAnD3U3V5QyHkQUEej2eZXRaa+qSbw2/IJJSPV0sPuAia1+'
53 | 'ccb7OnvxyZqkV9wQyimX6qAMz0K+UWFhQ5McCcQ/XsFhhezoVd5QgL7PtdvuK1AtjuzA3J9yzNmwuPssPnKnc='
54 | ),
55 | signature
56 | )
57 |
58 | def test_rsa_verify(self):
59 | public_key = (
60 | "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCYBzBmLLKYIbz/sgm4yxuNwpGbkN2Ccg3J"
61 | "hCsb5oG5SE35okz8dm/WNosA0/YJyxhMUw5tQS9gPFczKG42h34gpk2w3LbuvNDC5qQw5FV5"
62 | "iTqnZV4dLXC44TePogwNipEaoh8bA6Ymik+jDAbnnF0GybT5VXNV41YaFJc1IDwq7wIDAQAB"
63 | )
64 | signer = AllInPayRsaSigner(key=AllInPayRsaSigner.get_public_key(public_key), delimiter=b"&")
65 | signer.add_data('appid=00000051')
66 | signer.add_data('cusid=990581007426001')
67 | signer.add_data('randomstr=82712208')
68 | signer.add_data('signtype=RSA')
69 | signer.add_data('trxid=112094120001088317')
70 | signer.add_data('version=11')
71 | self.assertTrue(
72 | signer.verify(
73 | 'ce6EAOj4rhoBMJM5MJCNG4qQ/CVMTWkoRuSGpSzRAnD3U3V5QyHkQUEej2eZXRaa+qSbw2/IJJSPV0sPuAia1+'
74 | 'ccb7OnvxyZqkV9wQyimX6qAMz0K+UWFhQ5McCcQ/XsFhhezoVd5QgL7PtdvuK1AtjuzA3J9yzNmwuPssPnKnc='
75 | )
76 | )
77 |
78 | @pytest.mark.skip(reason="not support")
79 | def test_sm2_signer(self):
80 | private_key = (
81 | "MIGTAgEAMBMGByqGSM49AgEGCCqBHM9VAYItBHkwdwIBAQQgNqz1EieIP8QVzV7vEmx5e8f7XN7/MIzoeXgEinxcG0agCgYIKoEc"
82 | "z1UBgi2hRANCAAQNfkEgaCQ4cdZ4aD2LWMcnkk5LALQfL05oY8x8XQDIyUM44N15YcTwtFNvHYgyeNRa93vlEUutp935n6rp4yuf"
83 | )
84 | signer = AllInPayRsaSigner(key=AllInPayRsaSigner.get_private_key(private_key), delimiter=b"&")
85 | signer.add_data('appid=00000051')
86 | signer.add_data('cusid=990581007426001')
87 | signer.add_data('randomstr=75016315')
88 | signer.add_data('signtype=SM2')
89 | signer.add_data('trxid=112094120001088317')
90 | signer.add_data('version=11')
91 | signature = signer.signature
92 | self.assertTrue(signer.verify(signature))
93 | self.assertEqual(
94 | 'm4ki0xZ+19LtqjuyG8Qb0ytD3Q8B166mboCeg+6Ar1Z4XmQB14LrcfddkM121EbroDDnJ17bbJAH/S+8jus9iQ==', signature
95 | )
96 |
--------------------------------------------------------------------------------
/tox.ini:
--------------------------------------------------------------------------------
1 | [tox]
2 | envlist = py27,py34,py35,py36,py37,pypy,pypy3
3 |
4 | [testenv]
5 | usedevelop = True
6 | basepython =
7 | py27: python2.7
8 | py34: python3.4
9 | py35: python3.5
10 | py36: python3.6
11 | py37: python3.7
12 | pypy: pypy
13 | pypy3: pypy3
14 | deps =
15 | -rdev-requirements.txt
16 | commands =
17 | pytest -v
18 |
--------------------------------------------------------------------------------