Sindbad~EG File Manager

Current Path : /home/numerotech/paymentapi.numerotech.com/paymentapi/core/controller/
Upload File :
Current File : //home/numerotech/paymentapi.numerotech.com/paymentapi/core/controller/ApiController.py

from flask import Flask, request, Blueprint, jsonify, redirect, url_for,flash, render_template,session
from core.model.UserModel import UserModel
from core.model.APIModel import APIModel
from core.model.PayumoneyModel import PayumoneyModel
from core.model.InstamojoModel import InstamojoModel
from random import randint
import datetime
from datetime import timedelta,date,datetime
import requests, json
# from .. import Cryptography
from flask import session, app
from instamojo_wrapper import Instamojo

import hashlib
from .. import config
import flask
from flask_cors import CORS, cross_origin



import razorpay
import base64

app = Blueprint('api', __name__)

@app.route('/', methods = ["GET", "POST"])
def Index():
	# return redirect (url_for('bo.BOAdmin'))
	return render_template('users/welcomePage.html')


@app.route('/myapi', methods = ["GET", "POST"])
def MYAPIKey():
	data = {'name':'demo','key':'1231'}
	return json.dumps(data,default =str)
	

@app.route('/api_key', methods = ["GET", "POST"])
# @cross_origin(origin='*')
def APIKey():
	apikeys = UserModel().getApikeys()
	# apikeys.headers.add('Access-Control-Allow-Origin', '*')
	return json.dumps(apikeys,default =str)
	
@app.route('/gateway_settings/<int:am_id>', methods = ["GET", "POST"])
def GatewaySettings(am_id):
	apikeys = UserModel().getGatewaySettins(am_id)
	return json.dumps(apikeys,default =str)	
	

@app.route('/api_keyss', methods = ["GET", "POST"])
def APIKeyss():
	url = 'https://paymentapi.urbanedge.co.in/api_key'
	r = requests.get(url)
	data = json.loads(r.content.decode())
	return jsonify(data)


######### update in api controller for sirdhar anna using app master id 
@app.route('/payments/<am_id>', methods = ["GET", "POST"])
def Payments(am_id):
	# if request.method == 'POST':
	base64_bytes   = am_id.encode("ascii") 
	sample_bytes   = base64.b64decode(base64_bytes) 
	am_id_str = sample_bytes.decode("ascii")
	am_id_int = int(am_id_str)
	gateway_appmaster   = APIModel().getAppMasterGateway(am_id_int)
	gateway_name = gateway_appmaster["gateway_name"]
	

# 	return gateway_name
	# ------ Data from client side save in payment api database   ---- 
	now       = datetime.now()
	dt_string = now.strftime("%Y-%m-%d %H:%M:%S")
	
	name          = request.values.get("name","Ganesan")
	email         = request.values.get("email","ganesan@numerotec.om")
	mobile        = request.values.get("mobile","8637643225")
	amount        = request.values.get("amount","5.00")
	res_url       = request.values.get("res_url","https://paymentapi.kosonline.org")
	remarks       = request.values.get("remarks","Delegate Reg")
	
	unique_id     = request.values.get("unique_id","122222222")   # This is added on feb 23 2020 like order id
	# key           = request.values.get("key",None)   # This is added on sep 24 2020 for merchant ref id
	# key_unique_id =  key+"_"+str(unique_id)
	is_test       = request.values.get("is_test","1") or 0
	currency      = request.values.get("currency","INR" )
	
	am_id         = am_id_int

	
	
	if "." in amount :
		amount_int = amount
		amount_int = amount_int[:-3]
	else :
		amount_int = int(amount)
		
		
	if not currency :
		currency = "INR"
	else :
		currency = currency
		


	if float(amount_int) <=0 or res_url is None  :
		return  "Please enter response url and valid amount "
	else :
		# gateway_name = "RazorPay"
# 		currency     = "INR"
		
		data = {
			'name'         : name,
			'email'        : email,
			'mobile'       : mobile,
			'amount'       : amount,
			'gateway_name' : [gateway_name],
			'res_url'      : res_url,
			'is_test'      : [is_test],
			'remarks'      : remarks,
			#'key_unique_id': [key_unique_id],
			'am_id'        : [am_id],
			'created_at'   : [dt_string],
			'currency'     : [currency],
			'unique_id'    : unique_id
		}
		delg_save =UserModel().insert_delegates(data,unique_id)
		last_insert_id = delg_save

		# encode res_url
		url_byte   = res_url.encode("ascii") 
		_bytes     = base64.b64encode(url_byte) 
		r_url      = _bytes.decode("ascii")
	if  "Razor"  in gateway_name:   ######## Razorpay block
		if int(is_test) == 1 :
			# After save data in our database
			gateway_name = gateway_appmaster["gateway_name"]
			api_key_1    = gateway_appmaster["test_key"]
		else :
			gateway_name     = gateway_appmaster["gateway_name"]
			api_key_1        = gateway_appmaster["live_key"]
		 
		# delegates = UserModel().get_delegate_by_pid(last_insert_id)
		# amt = delegates.amount
		# amount = int(amt) * 100

		amount = int(amount_int) * 100

		return render_template('razorpay/razorpay_payment_screen.html',delegates = data,last_insert_id=last_insert_id,amount=amount,am_id=am_id,r_url=r_url,api_key_1=api_key_1,is_test =is_test)
	
	elif "Instam" in gateway_name : ########### instamojo block
		if int(is_test) == 1 :
			api_key_1     = gateway_appmaster["test_key"]
			auth_token_1  = gateway_appmaster["test_auth_token"]
			pay_link_1    = gateway_appmaster["pay_test_link"]
			api = Instamojo(api_key=api_key_1,auth_token=auth_token_1,endpoint='https://test.instamojo.com/api/1.1/')
		else :
			api_key_1     = gateway_appmaster["live_key"]
			auth_token_1  = gateway_appmaster["live_auth_token"]
			pay_link_1    = gateway_appmaster["pay_live_link"]
			api           = Instamojo(api_key=api_key_1,auth_token=auth_token_1,endpoint='https://instamojo.com/api/1.1/')


		p_id_ =str(last_insert_id)
		response    = api.payment_request_create(amount=amount, buyer_name= name,phone = mobile,purpose= "Delegate Registration fee" ,send_email=False,email=email,
		redirect_url="https://paymentapi.urbanedge.co.in/payment_api/payment_instamojo_response/"+p_id_+"?res_url="+res_url
		)
		
		
		
		pay_request_id     = response['payment_request']['id']
		payment_request_id = pay_request_id
		status             = response['payment_request']['status']  # Get the current status
		method             = "Card"
		
		now                = datetime.now()
		dt_string          = now.strftime("%Y-%m-%d %H:%M:%S")
		update_pay_req_id  = InstamojoModel().updatePayReqIdInstamojo(last_insert_id,pay_request_id,status,dt_string)
		return render_template('instamojo/instamojo_payment_screen.html',data= data,payment_request_id=pay_request_id,last_insert_id =last_insert_id,pay_link_1= pay_link_1)
	
	elif gateway_name == "Payumoney" :
		if int(is_test or 0) == 1 :
			MERCHANT_KEY   = gateway_appmaster["test_key"]
			key            = gateway_appmaster["test_key"]
			SALT           = gateway_appmaster["test_salt_or_secret"]
			PAYU_BASE_URL  = "https://sandboxsecure.payu.in/_payment"  # FOR TEST MODE
		else :
			MERCHANT_KEY = gateway_appmaster["live_key"]
			key          = gateway_appmaster["live_key"]
			SALT         = gateway_appmaster["live_salt_or_secret"]
			PAYU_BASE_URL= "https://secure.payu.in/_payment"  # FOR LIVE MODE


		action = ''
		if request.method == 'GET':
			posted={}

			return render_template('payumoney/payumoney_payment_screen.html',posted=posted,delegates=data,r_url = r_url,last_insert_id=last_insert_id) 
		else:
			posted={}
			# # Merchant Key and Salt provided y the PayU.
			# randtemp = randint(0,20)
			randtemp = str(randint(1,99999))+ str(unique_id)
			hash_object = hashlib.sha256(str(randtemp).encode('utf-8'))
			txnid= str(unique_id) + hash_object.hexdigest()[0:20]
			# txnid= 'VRVDC' + hash_object.hexdigest()[0:20]
			hashh = ''

			# Mandatory Field
			posted['amount'] = amount
			posted['productinfo']='register'
			posted['firstname'] = name
			posted['email'] = email
			posted['phone'] = mobile
			posted['surl'] = config['BASE_URL']+'/payment_api/success'
			posted['furl'] = config['BASE_URL']+'/payment_api/success' # status split in success function so 2 url is same.
			posted['hash'] = ''
			posted['udf1'] = r_url
			posted['udf2'] = unique_id   # this line added on feb 23 2020
			# hashSequence = "key|txnid|amount|productinfo|firstname|email|phone|surl|furl"
			hashSequence = "key|txnid|amount|productinfo|firstname|email|udf1|udf2|udf3|udf4|udf5|udf6|udf7|udf8|udf9|udf10"
			posted['txnid']=txnid
			posted['key']=key
			hash_string=''
			hashVarsSeq=hashSequence.split('|')
			for i in hashVarsSeq:
				try:
					hash_string+=str(posted[i])
				except Exception:
					hash_string+=''
				hash_string+='|'
			hash_string+=SALT
			hashh=hashlib.sha512(hash_string.encode('utf-8')).hexdigest().lower()
			action =PAYU_BASE_URL
			if(posted.get("key")!=None and posted.get("txnid")!=None and posted.get("firstname")!=None and posted.get("email")!=None):
				payment_id     = posted.get("txnid")
				payment_status = "Pending"
				created_at     = datetime.now()
				method = None

				insert_user    = PayumoneyModel().update_payment_id(last_insert_id,payment_id,payment_status,created_at)
				data = { "posted":posted,"hashh":hashh,"key":key,"MERCHANT_KEY":MERCHANT_KEY,"txnid":txnid,"action":action }  # It is base url assigned into action variable
				# data = { "posted":posted,"hashh":hashh,"key":key,"MERCHANT_KEY":MERCHANT_KEY,"txnid":txnid,"action":"https://secure.payu.in/_payment" }  # It is before mar 13 2021 .THIS LINE working fine
				# data = { "posted":posted,"hashh":hashh,"key":key,"MERCHANT_KEY":MERCHANT_KEY,"txnid":txnid,"hash_string":hash_string,"action":"https://sandboxsecure.payu.in/_payment" }
				return render_template('payumoney/payu_request.html',posted=data.get('posted'),MERCHANT_KEY=MERCHANT_KEY,action=action,hashh=hashh,txnid=txnid)
			else:
				data = { "posted":posted,"hashh":hashh,"MERCHANT_KEY":MERCHANT_KEY,"txnid":txnid,"hash_string":hash_string,"action":"." }
				return render_template('payumoney/payu_request.html',posted=data.get('posted'))	
				
				
	if  "Paypal"  in gateway_name:   ######## Paypal block#
		# test_key as client_id for paypal
		app_key         = gateway_appmaster["app_key"]
		if int(is_test) == 1 :
			client_id  = gateway_appmaster["test_key"]
		else :
			client_id  = gateway_appmaster["live_key"]
		# currency = "USD"	 # THIS IS MANUALLY PASS VALUE FOR TESTING BY Ganesan
		res_url = res_url+"?unique_id="+unique_id+"&email="+email	
		return render_template('paypal/paypal_screen.html',currency_code=currency,amount=amount,unique_id=unique_id,remarks=remarks,client_id=client_id,res_url=res_url,email= email,app_key=app_key)
		
	else :
		return "Error .Please try again."
		

# Webhook call payumoney account
# get webhook data by unique_id -- October 31, 2022	
@app.route('/payment_response_by_unique_id', methods = ["GET", "POST"])
def PaymentResponseByUniqueId():
	# return "Testing"
	try:
		now          = datetime.now()
		dt_string    = now.strftime("%Y-%m-%d %H:%M:%S")
		unique_ids   = request.values.get("unique_ids") or None
		unique_id_count = 0
		if unique_ids :
			print(unique_ids)
			if "," in unique_ids :
				list_1     = unique_ids.split(",")
				unique_id_count = len(list_1)
				list_1     = str(list_1)
				
				list_1     = list_1.replace("[" , "").replace("]" , "")
				unique_ids = list_1
			else : 
				pass	
				unique_id_count = 1
			
			# data = {"unique_ids" : unique_ids , "unique_id_count" : unique_id_count }
			# return (json.dumps(data,default=str) )
			payment_data = APIModel().getPaymentDataByUniqueId(unique_ids,unique_id_count)
			if payment_data :
				payment_data = {'payment_data' : payment_data , 'msg' : 'success' , 'status' : 1}
			else :
				payment_data = {'payment_data' : [] , 'msg' : 'No Record exists.' , 'status' : 2}	

			json_data = json.dumps(payment_data,default =str)
			return json_data
		else :
			payment_data = {'payment_data' : [] , 'msg' : 'Unique id is empty !.Please pass the unique-id to get data' , 'status' : 3}
			json_data = json.dumps(payment_data,default =str)
			return json_data	
	except Exception as e:
		payment_data = {'payment_data' : [] , 'msg' : str(e) , 'status' : 401}	
		json_data = json.dumps(payment_data,default =str)
		return json_data
		
		


	

Sindbad File Manager Version 1.0, Coded By Sindbad EG ~ The Terrorists