I am new to django, i am trying to integrate payumoney with my django project. but i am unable to integrate please anyone can give me the steps of payumoney integration.
#app.route('/flaskpayment/<cid>', methods=['GET', 'POST'])
#login_required
def flaskpayment(cid):
try:
with app.app_context():
form = PaymentForm()
if request.method == 'POST':
#read data from previous form
amount = request.form['amount']
firstname = request.form['fname']
email = request.form['email']
phone = request.form['phone']
productinfo = cid
MERCHANT_KEY = "XXXXXXX"
key="XXXXXXX"
SALT = "XXXXXXXX"
PAYU_BASE_URL = "https://test.payu.in/_payment"
posted={}
hash_object = hashlib.sha256(str(random.randint(0,20)))
txnid=hash_object.hexdigest()[0:24]
hashh = ''
posted['txnid']=txnid
hashSequence = key+'|'+txnid+'|'+amount+'|'+productinfo+'|'+firstname+'|'+email+'||||||||||'
posted['key']=key
hash_string = hashSequence
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).hexdigest().lower()
#Payumoney required parameters
form.key.data = MERCHANT_KEY
form.hash_string.data = hash_string
form.hash.data = hashh
form.posted.data = posted
form.firstname.data = firstname
form.email.data = email
form.txnid.data = txnid
form.amount.data = amount
form.phone.data = phone
#service_provider only for secure payment
form.service_provider.data = 'payu_paisa'
form.productinfo.data = cid
form.surl.data = 'https://www.yoursite.com/success/'
form.furl.data = 'https://www.yoursite.com/failure/'
return render_template('paymentform.html',form=form, action = PAYU_BASE_URL)
except Exception as e:
return str(e)
Please refer API documentation ,Integration doc,and website integration
here is an article you can definitely check it out for more information:-
https://makedeveasy.medium.com/payumoney-integration-with-django-rest-framework-and-javascript-19f266a6bad7
Related
Once I get to the verify_token function it keeps executing the except statement instead of returning the value in 'id_user' and I'm not sure why. I am using these libraries. flask-login, sqlalchemy, itsdangerous for jsonwebserializer, and wtforms.
Functions
def get_reset_token(user):
serial = Serializer(app.config['SECRET_KEY'], expires_in=900) # 15 mins in seconds
return serial.dumps({'id_user':user.id}).decode('utf-8')
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
user_id = serial.load(token)['id_user']
except:
return None
return Users.query.get('id_user')
def send_mail(user):
token = get_reset_token(user)
message = Message('Password Reset Request', recipients = [user.email], sender='noreply#gmail.com')
message.body= f'''
To Reset your password, click the following link:
{url_for('reset_token', token = token, _external = True)}
If you did not send this email, please ignore this message.
'''
mail.send(message)
ROUTES
#app.route('/password_reset', methods = ['GET', 'POST'])
def password_reset():
form = Password_request()
if request.method == "POST":
if form.validate_on_submit:
user = Users.query.filter_by(email = form.email.data).first()
send_mail(user)
flash('Check your email. Password change request has been sent')
return redirect(url_for('login'))
else:
flash('Your email was not linked to an account')
return render_template('password_reset.html', form = form)
#app.route('/password_reset/<token>', methods = ['GET', 'POST'])
def reset_token(token):
user = verify_token(token)
if user == None:
flash('The token is invalid or expired')
return redirect(url_for('password_reset'))
form = Password_success()
if form.validate_on_submit:
hashed_password=generate_password_hash(form.password.data, method = 'sha256')
user.password = hashed_password
db.session.commit()
flash('Your password has been updated!')
return redirect(url_for('signup'))
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
user_id = serial.load(token)['id_user']
except:
return None
return Users.query.get('id_user') # this looks wrong
Shouldn't the last line of verify_token be return Users.query.get(user_id)? You're assigning the value of the token to that variable , then ignoring it and telling SQLAlchemy to find a record with the ID of the string value 'id_user' which I doubt is what you're intending to do.
def verify_token(token):
serial = Serializer(app.config['SECRET_KEY'])
try:
user_id = serial.load(token)['id_user']
except:
return None
return Users.query.get(user_id) # What happens when you change this?
I am creating a simple directory with Flask & Pyrebase; I have managed to create the login ok, and the registration form. The user is redirected to their profile page once signed in & registered.
My issue that I have is when I try to add a new entry my existing data is overwritten. When I create a new db entry I use set() instead of push() I am thinking this could be why?
I have shortened the code us much as possible
creating account & registering business:
#app.route('/register', methods=['GET', 'POST'])
def register():
unsuccessful = 'Please check your credentials'
successful = 'Registraion successful'
if request.method == 'POST':
email = request.form.get('email')
confirmEmail = request.form('confirmEmail')
password = request.form.get('pass')
userName = request.form.get('inputName')
businessName = request.form.get('businessName')
startYear = request.form.get('startYear')
selectCategory = request.form.get('selectCategory')
businessDescription = request.form.get('businessDescription')
businessAddress = request.form.get('businessAddress')
businessTown = request.form.get('businessTown')
businessCity = request.form.get('businessCity')
businessPostcode = request.form.get('businessPostcode')
businessNumber = request.form.get('businessNumber')
businessEmail = request.form.get('businessEmail')
bameRegister = dict(
userName = userName,
confirmationEmail = confirmEmail,
businessName = businessName,
businessStartYear = startYear,
businessCategory = selectCategory,
businessDescription = businessDescription,
businessAddress = [businessAddress, businessTown, businessCity, businessPostcode],
businessNumber = businessNumber,
businessEmail = businessEmail,
)
if selectCategory == "arts":
try:
user = auth.create_user_with_email_and_password(email, password)
auth.send_email_verification(user['idToken'])
db.child("Bame_Buisness").child("business").child("arts").set(bameRegister, user['idToken'])
return render_template('homepage.html', x=successful)
except:
return render_template('homepage.html', y=unsuccessful)
elif selectCategory == "food":
try:
user = auth.create_user_with_email_and_password(email, password)
auth.send_email_verification(user['idToken'])
db.child("Bame_Business").child("business").child("food").set(bameRegister, user['idToken'])
return render_template('homepage.html', x=successful)
except:
return render_template('homepage.html', y=unsuccessful)
elif selectCategory == "health":
try:
user = auth.create_user_with_email_and_password(email, password)
auth.send_email_verification(user['idToken'])
db.child("Bame_Business").child("business").child("health").set(bameRegister, user['idToken'])
return render_template('homepage.html', x=successful)
except:
return render_template('homepage.html', y=unsuccessful)
return render_template('homepage.html')
Creating the login:
#app.route('/login', methods=['GET', 'POST'])
def login():
unsuccessful = 'Please check your credentials'
if request.method == 'POST':
try:
user = auth.sign_in_with_email_and_password(email, password)
signed_in_user = auth.get_account_info(user['idToken'])
artCategory = db.child("Bame_Business").child("business").child("arts").get(user['idToken']).val()
foodCategory = db.child("Bame_Business").child("business").child("food").get(user['idToken']).val()
healthCategory = db.child("Bame_Business").child("business").child("health").get(user['idToken']).val()
if signed_in_user['users'][0]['email'] == artCategory['confirmationEmail']:
return render_template('profile.html', artCategory=artCategory)
elif signed_in_user['users'][0]['email'] == foodCategory['confirmationEmail']:
return render_template('profile.html', foodCategory=foodCategory)
elif signed_in_user['users'][0]['email'] == healthCategory['confirmationEmail']:
return render_template('profile.html', healthCategory=heathCategory)
except:
return render_template('homepage.html')
return render_template('homepage.html')
This is the route to create a new business once logged in:
#app.route('newBusiness', methods=['GET', 'POST'])
def newBusiness():
if request.method == 'POST':
email = request.form.get('email')
confirmEmail = request.form.get('confirmEmail')
password = request.form.get('pass')
userName = request.form.get('userName')
businessName = request.form.get('businessName')
startYear = request.form.get('startYear')
selectCategory = request.form.get('selectCategory')
businessDescription = request.form.get('businessDescription')
businessAddress = request.form.get('businessAddress')
businessTown = request.form.get('businessTown')
businessCity = request.form.get('businessCity')
businessPostcode = request.get('businessPostcode')
businessNumber = request.form.get('businessNumber')
businessEmail = request.form.get('businessEmail')
bameRegister = dict(
userName = userName,
confirmationEmail = confirmEmail,
businessName = businessName,
businessStartYear = startYear,
businessCategory = businessCategory,
businessDescription = businessDescription,
businessAddress = [businessAddress, businessTown, businessCity, businessPostcode],
businessNumber = businessNumber,
businessEmail = businessEmail,
)
if selectCategory == "arts":
try:
user = auth.sign_in_with_email_and_password(email, password)
user = auth.refresh(user['refreshToken'])
db.child("Bame_Business").child("business").child("arts").set(bameRegister, user['idToken'])
signed_in_user = auth.get_account_info(user['idToken'])
artCategory = db.child("Bame_Business").child("business").child("arts").get(user['idToken']).val()
if signed_in_user['users'][0]['email'] == artCategory['confirmationEmail']:
return render_template('profile.html', artCategory=artCategory)
except:
return render_template('homepage.html')
elif selectCategory == "food":
try:
user = auth.sign_in_with_email_and_password(email, password)
user = auth.refresh(user['refreshToken'])
db.child("Bame_Business").child("business").child("food").set(bameRegister, user['idToken'])
signed_in_user = auth.get_account_info(user['idToken'])
foodCategory = db.child("Bame_Business").child("business").child("food").get(user['idToken']).val()
if signed_in_user['users'][0]['email'] == foodCategory['confirmationEmail']:
return render_template('profile.html', foodCategory=foodCategory)
except:
return render_template('homepage.html')
elif selectCategory == "health":
try:
user = auth.sign_in_with_emal_and_password(email, password)
user = auth.refresh(user['refreshToken'])
db.child("Bame_Business").child("business").child("health").set(bameRegister, user['idToken'])
signed_in_user = auth.get_account_info(user['idToken'])
healthCategory = db.child("Bame_Business").child("business").child("health").get(user['idToken']).val()
if signed_in_user['users'][0]['email'] == healthCategory['confirmationEmail']:
return render_template('profile.html', healthCategory=healthCategory)
except:
return render_template('homepage.html')
return render_template('homepage.html')
After the user has logged in, lets say they register their 1st business in the arts category, when they register their 2nd different business in the arts category the original collection is overwritten in Firebase. This happens even when selecting a different category. This is definitely not ideal as someone could overwrite someone else's data - which then leads to all sorts of problems!
I understand you can use push & set to create new entries in pyrebase; I chose set because when I used push it creates a unique tag which I found it hard to get individual access from a users account. With the set method it is easy to call out the part of the dictionary I want with artCategory['businessName'] or artCategory['businessDescription'] or artCategory['confirmationEmail'] etc
I just need to create a new business registration after login in without overriding any existing data, if anyone could help me come up with a solution that would be much appreciated.
Kind regards
.set() overrides. .update() updates only the fields that have changed.
I suspect it has something got to do with refresh token. Could not understand how to use it by the docs. Can I know the exact code how to use it?
The access token is created during login:
#app.route('/login', methods=['POST','GET'])
def login():
username = request.form["email"]
password = request.form["password"]
my_token_expiry_time = datetime.timedelta(seconds=60)
segments = 0
access_token = None
if request.method == 'POST':
result_set = authenticate_user(username, password)
if result_set:
ss1 = select([nsettings]).\
where(nsettings.c.mattribute == 'my_jwt_expiry_time_min')
rss1 = g.conn.execute(ss1)
if rss1.rowcount > 0:
for r in rss1:
my_token_expiry_time = datetime.timedelta(seconds=
(int(r[nsettings.c.mvalue])* 60))
else:
my_token_expiry_time = datetime.timedelta(
seconds=(2 * 60 *60)) # 2 hours
#print result_set, 'result_set result_set'
session['email'] = result_set['email']
access_token = create_access_token(
identity=username, expires_delta=my_token_expiry_time)
user_dict = result_set
if user_dict:
session['email'] = user_dict['email']
session['id'] = result_set['id']
# users and related views
session['access_token'] = access_token
print access_token, 'aaaaaaaaaaa'
return jsonify({
'email': session['email'],
'user_id': result_set['id'],
'access_token': access_token,
'id': session['id'],
}), 200
else:
return jsonify({'message': "Invalid credentials, retry"}), 401
return "True"
The flask api call to upload:
#app.route('/rt/api/v1.0/issues/<int:issue_id>/documents', methods=['POST'])
#jwt_required
def rt_doc_upload(issue_id):
'''
Upload documents for a rt ticket.
'''
# Iterate through the list of files, we don't care about the
# attribute name. We consider only the first file and ignore the
# rest.
if 'id' in session:
uploader = "3"
minternal_only = True
bool_internal_update = False
msg_str = None
for attr, document in request.files.iteritems():
trans = g.conn.begin()
try:
orig_filename = document.filename
filename, upload_folder = check_or_insert_document(
orig_filename, uploader)
new_doc = add_doc(orig_filename, filename)
print orig_filename, 'origooooo'
ins = archival_docs.insert().values(new_doc)
rs = g.conn.execute(ins)
doc_id = rs.inserted_primary_key[0]
filename = (str(doc_id) + '_' + orig_filename)
stmt = archival_docs.update().values(stored_name=filename).\
where(archival_docs.c.id == doc_id)
g.conn.execute(stmt)
document.save(os.path.join(upload_folder, filename))
mattach_doc_id = genUrl(doc_id)
trans.commit()
return jsonify(
{'issue_doc_id': rs.inserted_primary_key[0]}), 201
except Exception, e:
print e
trans.rollback()
return jsonify({'message': "Did not find any file"}), 400
return jsonify({'message': "UNAUTHORIZED"}), 401
When used with runserver and on commenting the jwt_required decorator I am able to upload and download files
Using sqlalchemy core, python and flask. The api call to upload worked for more than a month, but suddenly stopped working now
After authenticating a user, I am having trouble keeping a user logged in as they move through the website I have built. I have tried using cookies and sessions but I can't seem to get it to work.
I am sharing my code for login where I grab data to authenticate a user from an excel sheet that is populated at Sign Up
I locate the names of each team member to have them appear on the Team Page, which is where the user is redirected to after login
#app.route('/login',methods=['POST','GET'])
def login():
# get data from form
try:
username = str(request.form['username2'])
password2 = str(request.form['password2'])
teamname = str(request.form['teamname'])
print(username)
print(password2)
# read excel sheet
data = pd.read_excel("C:\\Users\\290002925\\Documents\\registration.xlsx")
for name in data['Team']:
if name == teamname:
team_info = data.loc[data['Team'] == teamname]
print(team_info)
team_info['FullName'] = team_info['FirstName'] + [' '] + team_info['LastName']
teamroster = team_info[['FullName']].copy()
finalteamroster = pd.DataFrame(teamroster, index=range(5))
print(finalteamroster)
print(len(finalteamroster))
finalteamroster.fillna(value='', inplace=True)
print(finalteamroster)
amember1 = finalteamroster.at[0,'FullName']
print(amember1)
amember2 = finalteamroster.at[1,'FullName']
print(amember2)
amember3 = finalteamroster.at[2,'FullName']
print(amember3)
amember4 = finalteamroster.at[3,'FullName']
print(amember4)
amember5 = finalteamroster.at[4,'FullName']
print(amember5)
This is where the authentication of the user comes in
for user in data['Email']:
#check username
if user == username:
passw = data.loc[data['Email'] == username]
# check password
print(passw)
test2 = passw.iat[0,3]
This is how I wrote out cookies but I think Session might be more useful
if test2 == password2:
# authenticated
print("User is authenticated")
response = render_template('teampage.html', teamname=teamname, member1=amember1, member2=amember2, member3=amember3, member4=amember4, member5=amember5)
response.set_cookie('userID', username)
return response
else:
print("Password is incorrect")
return render_template('login.html')
else:
print("Username is incorrect")
return render_template('index.html')
except:
print("fail")
return render_template('login.html')
Code for Teampage
#app.route('/teampage')
def teampage():
userid = request.cookies.get('userID')
return render_template('teampage.html', userid=userid)
HTML user reference
{{userid}}
It is a bit hard to understand your initial code but what I understand is that you need to maintain a User session-
#app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html', title=': Login')
if request.method == 'POST':
if YourMethodToCheckPassword==True:
session['username'] = request.form['user']
return redirect(url_for('home'))
And then use the Session object everywhere like-
#app.route('/home')
def home():
if 'username' in session:
return render_template("index.html", name=session['username'])
Inside your HTML use
{{ name }}
I have the following codes, I'm using pyramid_beaker + gunicorn + pyramid_jinja2.
I noticed that when user is logged in, if I quickly and repeatedly do a "GET" to "http://my_server_ip_adress/addClientPersonne", I got many times a permission deny as if the logged user doesn't have "add_client" permission which is not normal. When making a "print session" I can see that sometimes the session has all the authentications informations to allow user to access the link above but another time it doesn't and the access is deny...maybe my configurations about pyramid_beaker are not good? any suggestions?
thanks.
my production.ini file
[app:main]
use = egg:annuaireldap#main
pyramid.includes = pyramid_beaker
pyramid_jinja2
session.key = annuaireldap
session.secret = iuyryoiuiytghvfs-tifrsztft
session.cookie_on_exception = true
session.type = memory
my views.py
#view_config(route_name="Menu", renderer='templates/menu.jinja2', request_method='GET')
def menu(request):
bootstrap_css_url = request.static_url('annuaireldap:static/bootstrap.min.css')
bootstrap_js_url = request.static_url('annuaireldap:static/bootstrap.min.js')
jquery_js_url = request.static_url('annuaireldap:static/jquery.min.js')
custom_css_url = request.static_url('annuaireldap:static/custom_css.css')
to_rend = {'bootstrap_css':bootstrap_css_url,'bootstrap_js':bootstrap_js_url,'jquery_js':jquery_js_url,'custom_css':custom_css_url}
to_rend.update({'Menu_1':request.route_url('addClientPersonne'),
'Menu_2':request.route_url('addClientEntreprise'),
'Menu_3':request.route_url('SeeAll')})
return to_rend
#view_config(route_name='SeeAll', renderer='templates/menu.jinja2', request_method=('GET', 'POST'))
def seeall(request):
return {}
#view_config(route_name='login', renderer='templates/login.jinja2',
request_method=('GET', 'POST'))
def login(request):
bootstrap_css_url = request.static_url('annuaireldap:static/bootstrap.min.css')
bootstrap_js_url = request.static_url('annuaireldap:static/bootstrap.min.js')
jquery_js_url = request.static_url('annuaireldap:static/jquery.min.js')
custom_css_url = request.static_url('annuaireldap:static/custom_css.css')
settings = request.registry.settings
server_uri = settings['server_uri']
rendered_form = None
base_dn_user = settings['base_dn_user']
cl = Credentials().bind(request=request)
se_connecter = deform.form.Button(name='se_connecter',
title='se connecter')
form = deform.form.Form(cl, buttons=(se_connecter,))
url_redirect = request.route_url('login')
session = request.session
session.save()
if authenticated_userid(request):
url_redirect = request.route_url("Menu")
resp = HTTPFound(location=url_redirect)
return request.response.merge_cookies(resp)
if request.method == 'POST':
if 'se_connecter' in request.POST:
try:
deserialized = form.validate(request.POST.items())
username = deserialized['username']
password = deserialized['password']
server = Server(server_uri)
user_dn = 'uid=%s,%s'%(username, base_dn_user)
user_dn = 'cn=admin,dc=splynx,dc=lan'
password = '1235789'
conn = Connection(server, user=user_dn, password=password)
if conn.bind():
session[username] = ['agent']
remember(request, username)
url_redirect = request.route_url('Menu')
resp = HTTPFound(location=url_redirect)
return request.response.merge_cookies(resp)
except ValidationFailure as e:
rendered_form = e.render()
else:
rendered_form = form.render()
return {'bootstrap_css':bootstrap_css_url,
'bootstrap_js':bootstrap_js_url,
'jquery_js':jquery_js_url,
'rendered_form':rendered_form,
'custom_css':custom_css_url}
#view_config(route_name='addClientPersonne', permission='add_client',
request_method=('GET', 'POST'), renderer='templates/addPersonne.jinja2')
def addClientPersonne(request):
bootstrap_css_url = request.static_url('annuaireldap:static/bootstrap.min.css')
bootstrap_js_url = request.static_url('annuaireldap:static/bootstrap.min.js')
jquery_js_url = request.static_url('annuaireldap:static/jquery.min.js')
custom_css_url = request.static_url('annuaireldap:static/custom_css.css')
rendered_form = None
settings = request.registry.settings
cl = ClientPersonne().bind(request=request)
ajouter = deform.form.Button(name='Ajouter',
title='Ajouter')
form = deform.form.Form(cl, buttons=(ajouter,))
request.session.save()
if request.method == 'POST':
if 'Ajouter' in request.POST:
try:
server_uri = settings['server_uri']
server = Server(server_uri)
deserialized = form.validate(request.POST.items())
nom = deserialized['nom']
prenom = deserialized['prenom']
telephone = deserialized['telephone']
description = deserialized['description']
description = "" if description == colander.null else description
creator_dn = settings['creator_dn']
creator_pwd = settings['creator_pwd']
conn = Connection(server, user=creator_dn, password=creator_pwd)
base_clients_personnes = settings['base_clients_personnes']
new_user_dn = 'uid=%s,%s'%(get_token(14), base_clients_personnes)
if conn.bind():
attributes = {'telephoneNumber':telephone,
'sn':nom,
'cn':prenom}
if description:
attributes['description'] = description
conn.add(new_user_dn, ['person', 'uidObject'], attributes)
conn.unbind()
url_redirect = request.route_url('Menu')
resp = HTTPFound(location=url_redirect)
return request.response.merge_cookies(resp)
except ValidationFailure as e:
rendered_form = e.render()
except Exception as e:
rendered_form = form.render()
else:
rendered_form = form.render()
return {'bootstrap_css':bootstrap_css_url,
'bootstrap_js':bootstrap_js_url,
'jquery_js':jquery_js_url,
'rendered_form':rendered_form,
'custom_css':custom_css_url}
my root factory
class CustomResourceFactory():
__acl__ = [
(Allow, 'agent', {'add_client', 'modify_client', 'view_client', 'delete_client'}),
DENY_ALL
]
def __init__(self, request):
print "concombre"
pass
If you have gunicorn configured to fork then you can't use an in-memory session store as it will not be shared across processes. You can confirm that this is the issue by turning off forking in gunicorn or switching to a wsgi server like waitress that does not fork.
The issue is with the gunicorn multiple workers. If you run this code with single worker it will run fine. The user session in is in memory for that worker and will not accessible from other workers.
So when you login the user details will be with only that worker and when hit the next GET call the request will go to the different worker where it will not get the user details and it will deny your request.