Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from idied.repository import db
- import os
- import datetime
- from idied.auth.auth_required import auth_required_redirect_to_main
- import hmac
- import hashlib
- from flask_cors import cross_origin
- from flask_restx import Namespace, Resource, fields
- from bson.objectid import ObjectId
- import time
- import requests
- from flask import render_template, make_response, redirect, request
- # http://localhost | https://idied.org
- BASE_URL = os.getenv("BASE_URL")
- # http://localhost:5001/ | https://idied.org/api/
- API_URL = os.getenv("API_URL")
- secret = "..."
- def get_date_of_payment(days=30):
- date = datetime.datetime.now()
- delta = datetime.timedelta(days=days)
- time_in_30_days = date + delta
- return time_in_30_days.strftime("%d.%m.%Y")
- def get_payload(order_id):
- date_of_next_payment = get_date_of_payment()
- date_of_end_payment = get_date_of_payment(1000000) # id.doc.id#2
- return {
- "merchantAccount": "idied_org",
- "merchantDomainName": BASE_URL,
- "merchantTransactionSecureType": "AUTO", # should be hardcoded
- "orderReference": order_id, # unique ID of a purchase
- "orderDate": str(int(time.time())),
- "amount": "1.99",
- "currency": "USD",
- "productName": ["Monthly Subscription"],
- "productPrice": ["1.00"],
- "productCount": ["1"],
- "regularMode": "monthly",
- "regularOn": "1",
- "returnUrl": f"{API_URL}payment/return",
- "serviceUrl": f"{API_URL}payment/callback",
- "clientPhone": "+380507308141",
- "dateNext": date_of_next_payment,
- "dateEnd": date_of_end_payment, # id.doc.id#2
- }
- def generate_auth_signature(payload):
- res = (
- ";".join([
- payload["merchantAccount"],
- payload["merchantDomainName"],
- payload["orderReference"],
- payload["orderDate"],
- payload["amount"],
- payload["currency"],
- payload["productName"][0],
- payload["productCount"][0],
- payload["productPrice"][0],
- ])
- )
- _bytes = bytes(res, encoding='utf-8')
- _secret = bytes(secret, encoding='utf-8')
- md5 = hmac.new(_secret, _bytes, hashlib.md5)
- return md5.hexdigest()
- api = Namespace('/payment',
- description='A list of routes related to the users',
- decorators=[cross_origin()])
- def check_payment():
- orderReference = request.form["orderReference"]
- payload = {
- "transactionType": "CHECK_STATUS",
- "merchantAccount": "idied_org",
- "orderReference": orderReference,
- "merchantSignature": "",
- "apiVersion": "2"
- }
- signature = f"idied_org;{orderReference}"
- _bytes = bytes(signature, encoding='utf-8')
- _secret = bytes(secret, encoding='utf-8')
- md5 = hmac.new(_secret, _bytes, hashlib.md5)
- payload["merchantSignature"] = md5.hexdigest()
- response = requests.post('https://api.wayforpay.com/api', json=payload)
- return response.json()
- def update_payment_in_payments_db(payment):
- current_time = int(time.time())
- db.payments_collection.update_one(
- {"_id": ObjectId(payment["orderReference"])},
- {
- "$set": {
- "status": "paid",
- "paid_at": current_time
- }
- }
- )
- def update_payment_in_users_db(payment):
- db_payment = db.payments_collection.find_one(
- {"_id": ObjectId(payment["orderReference"])}
- )
- user_id = db_payment.get("user_id")
- current_time = int(time.time())
- paid_until = (
- db.users_collection.find_one(
- {"user_id": user_id},
- {"paid_until": 1, "_id": 0}
- )
- .get("paid_until", current_time)
- )
- # just_paid_until = paid_until + 2592000 # 1 month
- # 100 years. Fake value until we have a payment system
- just_paid_until = paid_until + 3153600000
- db.users_collection.update_one(
- {"user_id": user_id},
- {
- "$set": {"paid_until": just_paid_until}
- },
- )
- def inform_admin_about_payment_in_telegram():
- message = "Successful payment! 🔥"
- try:
- requests.post(
- f"https://idied.org/api/tg-report",
- json={
- "message": message
- }
- )
- except Exception as e:
- print(e)
- def construct_pre_payment(user_id) -> dict:
- current_time = int(time.time())
- payment = {
- "user_id": user_id,
- "status": "requested",
- "paid_at": -1,
- "created_at": current_time
- }
- return payment
- @api.route('')
- class UserOnline(Resource):
- @auth_required_redirect_to_main
- def get(self, user_info):
- user_id = user_info.get("user_id")
- payment = construct_pre_payment(user_id)
- order = db.payments_collection.insert_one(payment)
- order_id = str(order.inserted_id)
- payload = get_payload(order_id)
- signature = generate_auth_signature(payload)
- payload["merchantSignature"] = signature
- payload["clientAccountId"] = user_id
- payload["clientEmail"] = user_info.get("email")
- url = "https://secure.wayforpay.com/pay?behavior=offline"
- response = requests.post(url, data=payload)
- payment_url = response.json().get("url")
- print(payment_url)
- return redirect(payment_url)
- @api.route('/return')
- class UserOnline(Resource):
- def post(self):
- payment = check_payment()
- status = payment.get("transactionStatus")
- if status != "Approved":
- return redirect(f"{BASE_URL}/notes?paid=false")
- update_payment_in_payments_db(payment)
- update_payment_in_users_db(payment)
- inform_admin_about_payment_in_telegram()
- return redirect(f"{BASE_URL}/notes?paid=true")
- @api.route('/callback')
- class UserOnline(Resource):
- def post(self):
- return {}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement