I am trying to create multiple payment profiles for my customers auth net profile using the this method.
def createAuthnetPaymentProfile(profileID, tries = 3):
profile = client.factory.create("CreateCustomerPaymentProfile")
profile.merchantAuthentication = merchantAuthentication
profile.customerProfileId = profileID
profile.paymentProfile = getAuthnetProfile(profileID, tries).paymentProfiles
payment_simple_type = client.factory.create('PaymentType')
card_simple_type = client.factory.create('CreditCardSimpleType')
payment_simple_type.creditCard = card_simple_type
profile.payment = payment_simple_type
profile.payment.creditCard = card_simple_type
profile.validationMode.value = "none"
profileResult = makeAuthnetCall(client.service.CreateCustomerPaymentProfile, profile, tries)
checkForError(profileResult)
return profileResult.customerPaymentProfileId
However this returns this error AuthnetError: E00029: Payment information is required.
What might be the problem with my code.
Related
I am trying to build a simple numeric captcha for my contact page in Flask. The contact page end-point loads in GET mode and initializes the values of the captcha verification. When I submit the form in POST mode, I expect my user-entered form value to match the captcha value. However, it is not working as expected. I did some troubleshooting with print statements to see how the values are changing and it appears that the captcha variables are getting re-initialised with the POST operation. Can someone please suggest a workaround? My Python code is shared below:
#bp.route('/contact/', methods=('GET', 'POST'))
def contact():
# Initialize captcha values
cap_a = random.randint(0, 9)
cap_b = random.randint(0, 9)
cap_prod = cap_a * cap_b
print(cap_a, cap_b, cap_prod)
if request.method == "POST":
error = None
log_file = current_app.config['LOGFILE']
full_name = request.form['fullname']
email_addr = request.form['email']
phone_no = request.form['phone']
msg_body = request.form['message']
num_prod = request.form['verifycaptcha']
print(cap_a, cap_b, cap_prod)
print(full_name, email_addr, phone_no, msg_body, num_prod)
if not full_name:
error = 'Full name is required.'
elif not email_addr:
error = 'Email address is required.'
elif not msg_body:
error = 'Message body is required.'
if num_prod != cap_prod:
error = 'Incorrect captcha verification.'
if error is None:
# Perform some operations
pass
try:
with current_app.app_context():
mail = Mail()
mail.init_app(current_app)
mail.send(msg)
error = 'Mail sent successfully!'
except:
error = 'Mail engine error encountered. Please retry after some time.'
f = open(log_file, "a")
f.write('['+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+'] '+error+'\n')
f.close()
flash(error)
return render_template('contact.html',num_a = cap_a, num_b = cap_b)
cap_a = random.randint(0, 9)
cap_b = random.randint(0, 9)
cap_prod = cap_a * cap_b
these are 2 random numbers and you are creating cap_prod. You are not saving the cap_prod anywhere. You are instead calculating it again when POST request comes (this time it will be 2 new random numbers)
You need to save the captcha that you created during the GET, and then when the POST comes , compare with the value that was originally sent.
If you are going to support refresh-captcha image in the future (you need to have an API call that will generate a new captcha and save it)
I figured out the solution by storing the captcha variables in the session dictionary of Flask and checking for its existence before re-initialising the values.
def contact():
# Initialize captcha values
if 'product' not in session:
cap_a = random.randint(0, 9)
cap_b = random.randint(0, 9)
session['captcha_a'] = cap_a
session['captcha_b'] = cap_b
session['product'] = cap_a * cap_b
else:
cap_a = session.get('captcha_a')
cap_b = session.get('captcha_b')
if request.method == "POST":
pass
# Rest of the code
Working examples of the above solution can be found at Fadmeter.com and FadURL.com.
I am creating a python reaction tester and I wish to share scores to facebook, however the sdk is confusing me greatly. I have got an access token without prompting a log in page, and the token appears in the web browser instead of the login. This is the code I have and an image of the result:
def facebookShare():
appID = '[removed]'
appSecret = '[removed]'
authArguments = dict(client_id = appID,
client_secret = appSecret,
redirect_uri = 'http://localhost:8080/',
grant_type = 'client_credentials',
state='abc123')
authCommand = 'https://graph.facebook.com/v3.2/oauth/access_token?' + urllib.parse.urlencode(authArguments)
authResponse = os.startfile(authCommand)
try:
authAccessToken = urllib.parse.parse_qs(str(authResponse))['access_token']
graph = facebook.GraphAPI(access_token=authAccessToken, version="3.2")
facebookResponse = graph.put_wall_post('I got an average time of ' + averageTime + 'seconds!')
except KeyError:
errorWindow = tkinter.Toplevel(root, bg = "blue")
tkinter.Label(errorWindow, text = "Something Went Wrong.", bg = "red").pack()
Shouldn't it need to log in to generate the access token? How can I make this generate a log in so it can print to the user's wall how it is supposed to? What URL would I need to use to get a login dialog?
I have something that is happening in my django shell that I cannot explain and do not know how to fix;
def get_answer_dict(self, format = None, *args,**kwargs):
current_user = MyUser.objects.get(id = self.kwargs['pk2']) #current_user
print(current_user)
survey_team = Survey.objects.get(name= 'Survey Raphael') #survey team (to change to final one)
current_response = ResponseModel.objects.filter(user = current_user, survey = survey_team)[0] #current response
#print(current_response)
answer_list = current_response.answers.all()
#print(answer_list)
answer_dict = []
for answer in answer_list:
ans_body = answer.body
ans_json = json.loads(ans_body)
answer_dict.append(ans_json)
return answer_dict
The thing is that in my django shell the user is printed twice...
Do you have an idea why ?
I'm creating a product review website through web2py and have encountered difficulty whilst adding a search feature. Here's the code I have so far:
def index():
rows = db(db.reviews).select()
name_default = request.vars.name
body_default = request.vars.body
objects_default = request.vars.objects
form = SQLFORM.factory(
Field("Item Name", default = name_default),
Field("Body", default = body_default),
Field("Objects", default = objects_default),
formstyle = 'divs'
submit_button = "Search"
)
query = db.db1.id_user == auth.user_id
if form.process().accepted:
name = form.vars.name
body = form.vars.body
objects = form.vars.objects
count = db(query).count()
results = db(query).select(orderby=~db.db1.data)
msg = T("%s registers" % count)
return dict(form=form, msg=msg, results=results)
return locals()
The error I'm getting is a syntax error on line 23 character 28 (the submit_button = "Search" line).
I have a form in google app engine where I want to upload an image and all my text at the same time. Do I have to seperate this into two seperate pages and actions?
Here is my upload handler:
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def upload(self, reseller_id, imgfile):
upload_files = imgfile
blob_info = upload_files[0]
key = blob_info.key()
r = Reseller.get_by_id(reseller_id)
r.blob_key_logo = str(key)
r.put();
Here is my creation of a new reseller object:
class NewReseller(BaseHandler):
def get(self):
if self.user:
self.render("new_reseller.html")
else:
self.redirect("/display_resellers")
def post(self):
name = self.request.get('name')
website = self.request.get('website')
information = self.request.get('information')
address = self.request.get('address')
city = self.request.get('city')
state = self.request.get('state')
zipcode = self.request.get('zipcode')
email = self.request.get('email')
phone = self.request.get('phone')
r = Reseller( name = name,
website = website,
information = information,
address = address,
city = city,
state = state,
zipcode = zipcode,
email = email,
phone = phone)
r.put()
theresellerid = r.key().id()
#And then Upload the image
u = UploadHandler()
logo_img = u.get_uploads('logo_img')
u.upload(theid, logo_img)
self.redirect('/display_resellers')
I think my problem here is this line:
logo_img = u.get_uploads('logo_img')
it pops out the error message
for key, value in self.request.params.items():
AttributeError: 'NoneType' object has no attribute 'params'
Somehow I need this NewReseller class to inherit the .getuploads from BlobstoreUploadHandler so I can do:
logo_img = self.get_uploads('logo_img')
Or there is probably a better way because this seems a little messy.
So my question is how to upload files and data in one form on just one page. I could do it with two seperate pages. One for adding the reseller and one for adding the image but that seems over complicated.
I tried to follow some steps and clues from this question:
Upload files in Google App Engine
******Edit***** Working Implementation Below:
class EditReseller(BaseHandler, blobstore_handlers.BlobstoreUploadHandler):
def get(self, reseller_id):
if self.user:
reseller = Reseller.get_by_id(int(reseller_id))
upload_url = blobstore.create_upload_url('/upload')
image = True
if reseller.blob_key_logo is None:
image = False
self.render('edit_reseller.html', r=reseller, reseller_id=reseller_id, upload_url=upload_url, image=image)
else:
self.redirect('/admin')
class UploadHandler(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
reseller_id = self.request.get('reseller_id')
upload_files = self.get_uploads('logo_img')
if upload_files:
blob_info = upload_files[0]
key = blob_info.key()
r = Reseller.get_by_id(int(reseller_id))
r.blob_key_logo = str(key)
r.put();
name = self.request.get('name')
website = self.request.get('website')
information = self.request.get('information')
address = self.request.get('address')
city = self.request.get('city')
state = self.request.get('state')
zipcode = self.request.get('zipcode')
email = self.request.get('email')
phone = self.request.get('phone')
if name and website and information and email and phone and address and city and state and zipcode:
r = Reseller.get_by_id(int(reseller_id))
r.name = name
r.website = website
r.information = information
r.address = address
r.city = city
r.state = state
r.zipcode = zipcode
r.email = email
r.phone = phone
r.put()
else:
error = "Looks like your missing some critical info"
self.render("edit_reseller.html", name=name, website=website, information=information, address=address, city=city, zipcode=zipcode, email=email, phone=phone, error=error)
self.redirect("/edit_reseller/" + reseller_id)
You just need to put the logic of the UploadHandler inside the Reseller(BaseHandler) and make Reseller inherit from blobstore_handlers.BlobstoreUploadHandler.
The call to get_uploads fails, as the NewReseller Class does not inherit from BlobstoreUploadHandler. The BlobstoreUploadHandler class takes over the upload operation so you do not need to create a post method, just add the corresponding logic from post ( name = self.request.get('name'), r = Reseller(), r.put(), etc. ) and add it to the upload method.
You should not call or create a new a handler instance by hand (unless you know what you are doing), as it would be missing the things that make it work.
The complete app sample at the official docs, might also be helpful.