├── .gitignore ├── LICENSE ├── README.md ├── billingservice ├── .secret │ ├── __init__.py │ ├── botsecret.py │ └── rq_access.py ├── __init__.py ├── billing.service ├── billing_service.py └── worker.py ├── example ├── .secret │ ├── __init__.py │ ├── botsecret.py │ └── ymsecret.py ├── __init__.py ├── billing_service.py └── telegrambot.py ├── httpsserver ├── .secret │ ├── __init__.py │ ├── botsecret.py │ ├── rq_access.py │ └── ymsecret.py ├── __init__.py ├── billing_service.py ├── donate_form.html ├── hash_error.html ├── httpserver-ympayment.service ├── httpsserver.py ├── payment_form.html └── requirements.txt └── image └── ympic.png /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # open-ymds 2 | ## Open source yandex money donation service 3 | Прием платежей на Яндекс.Деньги физ. лица 4 | - онлайн платежи с карты, яндекса, телефона 5 | - добавление метки к платежу 6 | - получение и проверка оповещений на свой сервер 7 | - пример автоматизации подписки на Telegram бота 8 | 9 | ### Модули: 10 | * **money.yandex.ru** - именной кошелек на который получаем деньги 11 | 12 | * **httpsserver** - python сервер генерирующий страницы оплаты и принимающий оповещения от яндекса 13 | 14 | * **billingservice** - remote процедура, вызываемая после получения оповещения о платеже, работает с базой 15 | 16 | * **redis-server** - используется как сервер очередей для удаленного вызова процедур 17 | 18 | * **example/telegrambot** - пример генерации ссылок для оплаты Telegram ботом 19 | 20 | ### money.yandex.ru: 21 | ![yandex](/image/ympic.png) 22 | 1. Регистрируемся, повышаем статус кошелька до именного 23 | 2. **НАСТРОЙКИ->ВСЕ ОСТАЛЬНОЕ->HTTP УВЕДОМЛЕНИЯ** 24 | * Добавляем свой домен и секрет 25 | * Включаем уведомления 26 | 3. Поднимаем **redis-server**, вносим параметры доступа в **rq_access.py** 27 | 4. Получаем SSL сертификат на домен, например через letsencrypt 28 | 5. Поднимаем https сервер со своими параметрами, не забываем про фаервол если сервер не доступен 29 | 6. Прописываем в **httpsserver/.secret/ymsecret.py** **id** кошелька и **секрет** для уведомлений из настроек 30 | 7. Правим **httpserver-ympayment.service**, запускаем сервер под супервизором 31 | 8. На машине с базой правим **billing.service** и запускаем **systemd** для этого сервиса запустится **RQ worker** 32 | 9. Проверяем удаленный запуск процедур через очередь **Redis** 33 | 10. Опираясь на example добавляем генерацию ссылки оплаты в вашу функцию бота 34 | 35 | #### Пример работы 36 | 37 | Нажимаем **/subscribe** в [@AudioTubeBot](https://t.me/AudioTubeBot): 38 | - вызывается **generate_subscribe_link()** через **RedisQueue** 39 | - удаленная процедура генерирует ссылку, защищенную от изменений хэшем на основе токена бота 40 | - в базе данных создаются объекты **invoice** для каждого типа подписки 41 | - через **RQ** возвращаются ссылки, которые вставляются в отправленное ботом сообщение 42 | 43 | Переходим по ссылке: 44 | - попадаем в обработчик GET запроса на httpsserver 45 | - рассчитывается хэш, проверяется валидность ссылки, невалидная отклоняется 46 | - в кнопки подставляются данные из ссылки, в т.ч. label - уникальный идентификатор инвойса 47 | - к платежу прикрепляется label, при успешном платеже яндекс отправляет оповещение POST запросом 48 | - чтобы проверить его валидность - рассчитываем хэш на основе общего с яндексом секрета 49 | - из валидного запроса берем **label и operation_id**, вызываем удаленную процедуру **successful_payment_callback()** 50 | - удаленная процедура проверяет - нет ли такого id в списке завершенных операций, если нет - \ 51 | выполняет подписку и вносит **operation_id** в список завершенных операций 52 | - уведомляем пользователя, пишем лог 53 | 54 | #### Это и многое другое вот здесь: 55 | 56 | [@AudioTubeBot](https://t.me/AudioTubeBot) - лучший бот для работы с аудио (реально лучший) 57 | 58 | [@VideoTubeBot](https://t.me/VideoTubeBot) - лучший бот для работы с видео (реально лучший) 59 | 60 | [@MediaTube_stream](https://t.me/MediaTube_stream) - канал автора (не самый лучший, но подписывайтесь) 61 | 62 | [@MediaTube_chat](https://t.me/MediaTube_chat) - чат для вопросов и выражения благодарности 63 | 64 | Призываю всех желающих внести посильный вклад и замечания в работу над сервисом 65 | -------------------------------------------------------------------------------- /billingservice/.secret/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mediatube/open-ymds/26be17ef798bb640cd9d553ac232fcb2022a52cb/billingservice/.secret/__init__.py -------------------------------------------------------------------------------- /billingservice/.secret/botsecret.py: -------------------------------------------------------------------------------- 1 | botsecret = 'xxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyy' -------------------------------------------------------------------------------- /billingservice/.secret/rq_access.py: -------------------------------------------------------------------------------- 1 | host = 'xxx.xxx.xxx.xxx' 2 | port = 6379 3 | password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' -------------------------------------------------------------------------------- /billingservice/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mediatube/open-ymds/26be17ef798bb640cd9d553ac232fcb2022a52cb/billingservice/__init__.py -------------------------------------------------------------------------------- /billingservice/billing.service: -------------------------------------------------------------------------------- 1 | [Service] 2 | Type=simple 3 | WorkingDirectory=/home/youruser/billingservice/ 4 | ExecStart=/usr/bin/python3.6 /home/youruser/billingservice/worker.py billing 5 | Restart=always 6 | RestartSec=10 7 | SyslogIdentifier=python-worker-billing 8 | User=youruser 9 | [Install] 10 | WantedBy=multi-user.target -------------------------------------------------------------------------------- /billingservice/billing_service.py: -------------------------------------------------------------------------------- 1 | import hashlib 2 | import imp 3 | 4 | # invoices - коллекция/таблица с объектами инвойсов для каждого пользователя 5 | # один инвойс может быть использован сколько угодно раз - например ежемесячная подписка 6 | # operations - коллекция/таблица с завершенными платежами, может быть несколько уведомлений на один платеж 7 | 8 | # Секрет на ваше усмотрение, используется для создания хэша, подписывающего ссылку, токен бота - удобно 9 | # Если изменится какой либо параметр ссылке - сервер может это проверить зная секрет и вычислив хэш 10 | with open('.secret/botsecret.py', 'rb') as fp: 11 | bottoken = imp.load_module('botsecret', fp, '.secret/botsecret.py', ('.py', 'rb', imp.PY_SOURCE)).bottoken 12 | 13 | 14 | # Функция, вызываемая через redis удаленно - возвращает ссылку для каждого пользователя, создавая инвойс в базе 15 | def get_invoice_link(user_id: str, months:str, price: str): 16 | # Генерируем ссылку на инвойс 17 | param_str = '&{0}&{1}&{2}&{3}'.format(str(user_id), str(months), str(price), bottoken) 18 | 19 | # Хэш с токеном бота в качестве секрета 20 | hash_sha1 = hashlib.sha1() 21 | hash_sha1.update(param_str.encode('utf-8')) 22 | invoice_hash = str(hash_sha1.hexdigest()) 23 | 24 | # Конечная ссылка на страницу оплаты 25 | link = 'https://yourdomain.xyz/generate?page=subscribe' \ 26 | '&uid={0}&months={1}&sum={2}&hash={3}'.format(user_id, months, price, invoice_hash) 27 | 28 | # ID пользователя гарантированно уникален, хэш - нет -> объединяем в метку платежа label 29 | # По полю label строим индекс в СУБД 30 | invoice = {'label': f'{user_id}:{invoice_hash}', 31 | 'user_id': f'{user_id}', 32 | 'months': f'{months}', 33 | 'price': f'{price}', 34 | 'link': f'{link}'} 35 | # Ищем существующий инвойс, если нет - создаем новый 36 | invoice_id = 'id' # invoices.find_one({'label': f'{user_id}:{invoice_hash}'}) 37 | if not invoice_id: 38 | invoice_id = 'id' # invoices.insert_one(invoice).inserted_id 39 | 40 | # Возвращаем ссылку 41 | return link 42 | 43 | 44 | # Эту функцию удаленно вызывает сервер, после получения оповещения и проверки его валидности 45 | def successful_payment_callback(invoice_label: str, operation_id: str, datetime: str): 46 | # Проверяем - нет ли в базе завершенной операции с таким id - если есть - выходим 47 | completed = False # db.operations.find_one({'id': f'{operation_id}'}) 48 | if not completed: 49 | # Достаем из базы инвойс по уникальной метке 50 | invoice = {} # db.invoices.find_one({'label': invoice_label}) 51 | # Вызываем целевую функцию, которая, например подписывает на оплаченный срок 52 | subscribe_user(int(invoice['user_id']), int(invoice['months'])) 53 | # Добавляем операцию в список завершенных 54 | operation = {'id': f'{operation_id}', 'datetime': f'{datetime}'} 55 | completed_id = 'id' # db.operations.insert_one(operation).inserted_id 56 | return completed_id 57 | return 58 | 59 | 60 | def subscribe_user(user_id: int, months: int): 61 | # Ваша функция подписки 62 | return 63 | -------------------------------------------------------------------------------- /billingservice/worker.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from redis import Redis 4 | from rq import Connection, Worker 5 | 6 | import imp 7 | 8 | with open('.secret/rq_access.py', 'rb') as fp: 9 | rq_access = imp.load_module('rq_access', fp, '.secret/rq_access.py', ('.py', 'rb', imp.PY_SOURCE)) 10 | redis_conn = Redis(host=rq_access.host, port=rq_access.port, password=rq_access.password) 11 | 12 | with Connection(redis_conn): 13 | qs = sys.argv[1:] or ['default'] 14 | w = Worker(qs) 15 | w.work() 16 | -------------------------------------------------------------------------------- /example/.secret/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mediatube/open-ymds/26be17ef798bb640cd9d553ac232fcb2022a52cb/example/.secret/__init__.py -------------------------------------------------------------------------------- /example/.secret/botsecret.py: -------------------------------------------------------------------------------- 1 | botsecret = 'xxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyy' -------------------------------------------------------------------------------- /example/.secret/ymsecret.py: -------------------------------------------------------------------------------- 1 | ymsecret = 'xxxxxxxxxxxxxxxxxxxxx' 2 | ym_account_id = '1234567890' -------------------------------------------------------------------------------- /example/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mediatube/open-ymds/26be17ef798bb640cd9d553ac232fcb2022a52cb/example/__init__.py -------------------------------------------------------------------------------- /example/billing_service.py: -------------------------------------------------------------------------------- 1 | def get_invoice_link(user_id, months, price): 2 | return 3 | 4 | 5 | def successful_payment_callback(invoice_label: str, operation_id: str, datetime: str): 6 | return 7 | 8 | 9 | def subscribe_user(user_id: int, months: int): 10 | return 11 | -------------------------------------------------------------------------------- /example/telegrambot.py: -------------------------------------------------------------------------------- 1 | from . import billing_service 2 | from redis import Redis 3 | from rq import Queue 4 | import imp 5 | 6 | with open('.secret/rq_access.py', 'rb') as fp: 7 | rq_access = imp.load_module('rq_access', fp, '.secret/rq_access.py', ('.py', 'rb', imp.PY_SOURCE)) 8 | # Подключаемся к соответствующей очереди redis через которую вызываем удаленные процедуры 9 | redis_conn = Redis(host=rq_access.host, port=rq_access.port, password=rq_access.password) 10 | q_billing = Queue(connection=redis_conn, name='billing', default_timeout=3600) 11 | 12 | # Пример функции генерирукщей ссылки из шаблона 13 | def show_pay_subscribe_message(message): 14 | # Читаем текстовый файл с шаблонами для ссылок 15 | # ... 16 | # Подписка 1200 мес 17 | # 👉Yandex Money 600р 18 | # 👉Картой 600р 19 | # 👉С мобильного 600р 20 | # ... 21 | # #Генерируем соответствующую ссылку и заменяем в тексте 22 | # message_to_send = message_to_send.replace('%SUBSCRIBELINK1200%', generate_subscribe_link(user_id, 1200, 600)) 23 | # bot.send_message(chat_id, parse_mode='HTML', text=message_to_send, disable_web_page_preview=True, 24 | # disable_notification=True) 25 | return 26 | 27 | 28 | def generate_subscribe_link(user_id, months, price): 29 | job_dl = q_billing.enqueue(billing_service.get_invoice_link, str(user_id), str(months), str(price)) 30 | while job_dl.result is None: 31 | job_dl.refresh() 32 | if job_dl.is_failed: 33 | raise Exception 34 | return job_dl.result 35 | -------------------------------------------------------------------------------- /httpsserver/.secret/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mediatube/open-ymds/26be17ef798bb640cd9d553ac232fcb2022a52cb/httpsserver/.secret/__init__.py -------------------------------------------------------------------------------- /httpsserver/.secret/botsecret.py: -------------------------------------------------------------------------------- 1 | botsecret = 'xxxxxxxxxxx:yyyyyyyyyyyyyyyyyyyyyyy' -------------------------------------------------------------------------------- /httpsserver/.secret/rq_access.py: -------------------------------------------------------------------------------- 1 | host = 'xxx.xxx.xxx.xxx' 2 | port = 6379 3 | password = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx' -------------------------------------------------------------------------------- /httpsserver/.secret/ymsecret.py: -------------------------------------------------------------------------------- 1 | ymsecret = 'xxxxxxxxxxxxxxxxxxxxx' 2 | ym_account_id = '1234567890' -------------------------------------------------------------------------------- /httpsserver/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mediatube/open-ymds/26be17ef798bb640cd9d553ac232fcb2022a52cb/httpsserver/__init__.py -------------------------------------------------------------------------------- /httpsserver/billing_service.py: -------------------------------------------------------------------------------- 1 | def get_invoice_link(user_id, months, price): 2 | return 3 | def successful_payment_callback(invoice_label: str,operation_id: str,datetime: str): 4 | return 5 | def subscribe_user(user_id, months): 6 | return -------------------------------------------------------------------------------- /httpsserver/donate_form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | MediaTube donate 7 | 27 | 28 | 29 |
30 | Поддержать разработчика 31 | 33 |
34 | 35 | 36 | -------------------------------------------------------------------------------- /httpsserver/hash_error.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | MediaTube subscription 7 | 27 | 28 | 29 |
30 | Ошибка хеша
31 | Ссылка недействительна, возможно она устарела.
32 | А возможно кто-то считает себя самым хитрым.
33 | 34 | /subscribe - сгенеровать новые ссылки
35 | 36 |
37 | 38 | 39 | -------------------------------------------------------------------------------- /httpsserver/httpserver-ympayment.service: -------------------------------------------------------------------------------- 1 | [Unit] 2 | Description=Simple HTTPS YM Payment server 3 | 4 | [Service] 5 | WorkingDirectory=/home/youruser/open-ymds/httpsserver 6 | ExecStart=/usr/bin/python3.4 /home/youruser/open-ymds/httpsserver/httpsserver.py 7 | Restart=always 8 | RestartSec=10 9 | SyslogIdentifier=python-httpsserverpayment 10 | User=youruser 11 | [Install] 12 | WantedBy=multi-user.target 13 | -------------------------------------------------------------------------------- /httpsserver/httpsserver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3.4 2 | import hashlib 3 | import re 4 | import ssl 5 | from . import billing_service 6 | from redis import Redis 7 | from rq import Queue 8 | from http.server import HTTPServer, SimpleHTTPRequestHandler 9 | from urllib import parse 10 | import imp 11 | 12 | with open('.secret/botsecret.py', 'rb') as fp: 13 | botsecret = imp.load_module('botsecret', fp, '.secret/botsecret.py', ('.py', 'rb', imp.PY_SOURCE)).botsecret 14 | with open('.secret/ymsecret.py', 'rb') as fp: 15 | ymsecret = imp.load_module('ymsecret', fp, '.secret/ymsecret.py', ('.py', 'rb', imp.PY_SOURCE)).ymsecret 16 | ym_account_id = imp.load_module('ymsecret', fp, '.secret/ymsecret.py', ('.py', 'rb', imp.PY_SOURCE)).ym_account_id 17 | with open('.secret/rq_access.py', 'rb') as fp: 18 | rq_access = imp.load_module('rq_access', fp, '.secret/rq_access.py', ('.py', 'rb', imp.PY_SOURCE)) 19 | 20 | redis_conn = Redis(host=rq_access.host, port=rq_access.port, password=rq_access.password) 21 | q_billing = Queue(connection=redis_conn, name='billing', default_timeout=3600) 22 | post_data_last = None 23 | 24 | 25 | class S(SimpleHTTPRequestHandler): 26 | def _set_headers(self): 27 | raw_url = str(self.path) 28 | if raw_url.find('yourdomain.xyz/generate?page=') != -1: 29 | self.send_response(200) 30 | self.send_header('Content-type', 'text/html') 31 | self.end_headers() 32 | else: 33 | self.send_response(403) 34 | 35 | def do_GET(self): 36 | self._set_headers() 37 | # self.send_header('Content-type', 'text/html') 38 | raw_url = self.path 39 | try: 40 | parsed_url = parse.parse_qs(raw_url) 41 | page_type = str(parsed_url['/generate?page'][0]) 42 | if page_type == 'subscribe': 43 | user_id = int(parsed_url['uid'][0]) 44 | months = int(parsed_url['months'][0]) 45 | sumrub = int(parsed_url['sum'][0]) 46 | security = str(parsed_url['hash'][0]) 47 | param_str = '&{0}&{1}&{2}&{3}'.format(str(user_id), str(months), str(sumrub), botsecret) 48 | hash_sha1 = hashlib.sha1() 49 | hash_sha1.update(param_str.encode('utf-8')) 50 | computed_hash = str(hash_sha1.hexdigest()) 51 | print(security, computed_hash) 52 | if computed_hash == security: 53 | invoice_label = '{0}:{1}'.format(user_id, computed_hash) 54 | base_page = open('payment_form.html', 'r').read() 55 | generated_page = re.sub('%DEFAULTSUM%', str(sumrub), base_page) 56 | generated_page = re.sub('%USERID%', str(user_id), generated_page) 57 | generated_page = re.sub('%TRANSACTIONLABEL%', str(invoice_label), generated_page) 58 | generated_page = re.sub('%YMACCOUNTID%', str(ym_account_id), generated_page) 59 | else: 60 | generated_page = open('hash_error.html', 'r').read() 61 | self.wfile.write(generated_page.encode('utf-8')) 62 | elif page_type == 'donate': 63 | base_page = open('donate_form.html', 'rb').read() 64 | self.wfile.write(base_page) 65 | else: 66 | self.send_response(403) 67 | except Exception: 68 | self.send_response(403) 69 | 70 | def do_HEAD(self): 71 | self._set_headers() 72 | 73 | def do_POST(self): 74 | content_length = int(self.headers['Content-Length']) # <--- Gets the size of data 75 | post_data = self.rfile.read(content_length) # <--- Gets the data itself 76 | input_data = post_data.decode('utf-8') 77 | parsed_data = parse.parse_qs(input_data) 78 | shared_secret = ymsecret 79 | # notification_type & operation_id & amount & currency & datetime & sender & codepro & notification_secret & 80 | # label 81 | operation_id = '{}'.format(parsed_data['operation_id'][0]) 82 | datetime = '{}'.format(parsed_data['datetime'][0]) 83 | 84 | verify_str = '{}&'.format(parsed_data['notification_type'][0]) 85 | verify_str += '{}&'.format(parsed_data['operation_id'][0]) 86 | verify_str += '{}&'.format(parsed_data['amount'][0]) 87 | verify_str += '{}&'.format(parsed_data['currency'][0]) 88 | verify_str += '{}&'.format(parsed_data['datetime'][0]) 89 | verify_str += '{}&'.format(parsed_data['sender'][0]) 90 | verify_str += '{}&'.format(parsed_data['codepro'][0]) 91 | verify_str += '{}&'.format(shared_secret) 92 | try: 93 | invoice_label = '{}'.format(parsed_data['label'][0]) 94 | except Exception: 95 | invoice_label = '' 96 | verify_str += invoice_label 97 | hash_sha1 = hashlib.sha1() 98 | hash_sha1.update(verify_str.encode('utf-8')) 99 | computed_hash = str(hash_sha1.hexdigest()) 100 | incoming_hash = parsed_data['sha1_hash'][0] 101 | print(incoming_hash, computed_hash) 102 | 103 | # logging.info("POST request,\nPath: %s\nHeaders:\n%s\n\nBody:\n%s\n", 104 | # str(self.path), str(self.headers), post_data.decode('utf-8')) 105 | # post_data_last = post_data 106 | if incoming_hash == computed_hash: 107 | job_dl = q_billing.enqueue(billing_service.successful_payment_callback, invoice_label, operation_id, 108 | datetime) 109 | while job_dl.result is None: 110 | job_dl.refresh() 111 | if job_dl.is_failed: 112 | raise Exception 113 | print(post_data.decode('utf-8')) 114 | self.send_response(200) 115 | # self.wfile.write("POST request for {}".format(self.path).encode('utf-8')) 116 | 117 | 118 | def run(server_class=HTTPServer, handler_class=S, port=443): 119 | server_address = ('', port) 120 | httpd = server_class(server_address, handler_class) 121 | httpd.socket = ssl.wrap_socket(httpd.socket, keyfile='/etc/letsencrypt/live/yourdomain.xyz/privkey.key', 122 | certfile='/etc/letsencrypt/live/yourdomain.xyz/certificate.crt', server_side=True) 123 | print('Starting httpd...') 124 | httpd.serve_forever() 125 | 126 | 127 | if __name__ == "__main__": 128 | from sys import argv 129 | 130 | if len(argv) == 2: 131 | run(port=int(argv[1])) 132 | else: 133 | run() 134 | -------------------------------------------------------------------------------- /httpsserver/payment_form.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | MediaTube subscription 7 | 8 | 35 | 36 | 37 |
38 |
Картой
39 |
40 | 42 |
43 |
44 |
45 |
Яндекс.Деньги
46 |
47 | 49 |
50 |
51 |
52 |
С мобильного
53 |
54 | 56 |
57 |
58 | 59 | 60 | 61 | -------------------------------------------------------------------------------- /httpsserver/requirements.txt: -------------------------------------------------------------------------------- 1 | rq 2 | redis 3 | -------------------------------------------------------------------------------- /image/ympic.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mediatube/open-ymds/26be17ef798bb640cd9d553ac232fcb2022a52cb/image/ympic.png --------------------------------------------------------------------------------